Jump to content
  • Advertisement
Sign in to follow this  

[C++] object slicing

This topic is 3471 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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 this post

Link to post
Share on other sites
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)

void X::swap(X& other) //doesn't throw
x.swap(other.x); //vector::swap doesn't throw

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.)

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!