If an object is passed to its class' copy constructor, is there a way for it to know that?
Code://Can "copy" know it's being copied? SomeClass& SomeClass::SomeClass(SomeClass const& copy) { ... }
If an object is passed to its class' copy constructor, is there a way for it to know that?
Code://Can "copy" know it's being copied? SomeClass& SomeClass::SomeClass(SomeClass const& copy) { ... }
You can call any const function on copy to have it do some processing while it is being copied. However, because it is const, that processing should not change the logical state of the copy object.
If you want to actually change the logical state of the copy object, you should make the reference not const. Then you can call any member function on copy that you want. However, this should be done rarely (if ever) because it changes the normal copy semantics. You would not expect that making a copy of an object would change that object.
One example of a class that changes the source of the copy is auto_ptr. It transfers ownership of the raw pointer from the source to the target of the copy. This leads to issues like the fact that you cannot use auto_ptr inside many standard containers because the strange copying semantics make the pointer get deleted prematurely.
Can you explain why you want the copy to know that it is being copied? Perhaps there is a better solution.
BTW, a copy constructor doesn't have a return type, it should be:Code://Can "copy" know it's being copied? SomeClass::SomeClass(SomeClass const& copy) { ... }
Last edited by Daved; 04-28-2008 at 12:35 PM.
Of course, because the copy constructor is part of the class. Therefore you have direct access to the internals of "copy" as well as "this." In other words, you are basically "both objects at once".
So if "copy" needs to have something done to it during the copy, just do it. Where else would you do it, anyway?
To get around the fact that only const member functions can be called... You can still modify member variables declared as mutable, but you should make sure that any variables declared as mutable don't affect the logical state of the object.
And if the copy constructor really DOES need to twiddle the internals of "copy" then perhaps it should be passed in as non-const, although I'm inherently suspicious of any design which does that. For one thing, passing a non-const reference to the copy constructor makes it impossible to use it with temporaries, which is a huge limitation (so much so that it's essentially useless).