Typically a user would expect that after an assignment x = y
, the equality x == y
should be true: assignment confers semantic equivalence. Doing anything else would be highly unusual and surprising. That probably includes not throwing an exception in response to the instruction "make x
like y
".
operator = on vectors of different dimensions
-
10-10-2022 - |
Question
consider the following code:
class vector{
// ...
vector(int size){ /*...*/ };
vector& operator= (const vector& other){
// ...
}
};
int main(){
vector v1(5), v2(10);
v1 = v2;
}
What is my operator =
supposed to do here? v1
does not have enough capacity to store the elements of v2
. From my point of view, it can either reinitialize itself to a capacity of 10 and copy the other vector's elements or throw an exception. I usually choose the former approach but increasingly often see the latter one. Which one is the correct one?
Solution
OTHER TIPS
It all depends on what a vector
is.
If it's an automatic resizing vector, you would expect a resize. std::vector
does just that.
If it's a mathematical vector for matrix operations, where you don't allow the vector size to change, then it should throw an exception.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow