Home > Software engineering >  Do instances of this clone method point back to the original object?
Do instances of this clone method point back to the original object?

Time:06-10

I'm not a C guru, navigating some code from an open source project trying to resolve an issue we have with the Java interface and the documentation is terrible. We've resolved that it may be due to the fact that a cloned object is what is used and not the originally instantiated object. The clone is created in the following method:

Base* Computer::Clone() const
{
   Base *clone = new Computer(*this);
   return (clone);
}

Computer is a subclass of Base so it returns a pointer to a Base object, created using the constructor of the same class, Computer and is done so via dereference (I believe thats what this is called here) with *this.

Now assuming Computer has an attribute bool isModeConfigured, if that is set to false for the original object, if the clone sets its to true does that replicate through? My inclination here is to say no, given the use of new.

CodePudding user response:

This expression new Computer(*this) calls the copy constructor Computer::Computer(const Computer&), whatever happens in there depends on its implementation.

Default implementation provided by the compiler (given the requirements for its generation are met) does member-wise copy of all attributes. "copy" means calling copy constructors of all members, same as above.

If you have

class Computer{
bool member;
}

Then the new instance has a copy of member and changing it on one object leaves the other unaffected. Hence both objects are totally independent.

AFAIK all C containers have the sane semantics and copies are independent of each other. The problem is with any kind of pointer, since default implementation (even for smart ones) is to make shallow copies. If you had (and you shouldn't) bool* member, both objects would share the pointed-to object.

Note: Never use new (unless you have to but those cases are rare), the modern, safe implementation is

std::unique_ptr<Base> Computer::Clone() const
{
   return std::make_unique<Computer>(*this);
}
  •  Tags:  
  • c
  • Related