Friday, April 4, 2014

Does destruction change anything?

class C{};

// consider this

void foo(const C* p)
{
    delete p;
}

// does it work? should it work?
// after all destroyng the object very much changes it 
// and you are not allowed to change a const object, right?
// ...
// now consider this
// (you can substitute here auto_ptr 
// with your favorite smart pointer)

void foo(auto_ptr<const C> p) { }

// is this possible at all?
// ...
// how about this

void foo(const C x) { }

// hmm... this is pretty common code
// if const objects exist (and we know they do) 
// then they must come to an end somehow

// so it is possible and completely normal to destroy 
// a constant object and all of the above is valid code

// so now my interpretation of const is this:
// if the object still exists, 
// its observable state should be the same as before

Based on this post on SO

No comments:

Post a Comment