# [C++] object slicing

## Recommended Posts

rozz666    896
Consider this class:
struct A {

std::vector<int> x;
std::vector<int> y;

// default copy constructor
// default destructor
// default assignment operator

};

Now consider this code:
A a1, a2;

a1 = a2;

if A::y's (A::x's depending which is assigment as second) assigment operator throws an exception, a1 is sliced. So does that mean that I always have to override the default assignment operator if one of the member variables' assigmnet operator throws an exception?

##### Share on other sites
visitor    643
This is not exactly what is called "slicing" (which might happen in case of inherited classes).

I suppose if you are worried about data integrity in case of exceptions, you might implement the operator= in terms of copy constructor and fast nothrow swap.

X& X::operator=(const X& rhv){   X(rhv).swap(*this);}void X::swap(X& other) //doesn't throw{    x.swap(other.x); //vector::swap doesn't throw    y.swap(other.y);}

This might be slower, though, since it always requires allocating new memory, but should be safer, because nothing is done to the lhv object until all risky operations are completed successfully.

(But then, since the default assignment might not even need additional memory, and if it is the allocations you are worried about (the assignment operator of contained objects in the vector might also throw or not), the safer version might actually throw more often ... Personally, as a hobbyist I haven't written anything needing as much safety as to worry about this, as I've never had a memory allocation fail in a correct program (and if it does my programs don't deal with important data.)