Is there an easy way to copy an instance of a class in C++?
Solution 1:
use default constructors like
Level(Level &&)
orLevel(const Level &)
-
Level(Level &&)
is the move constructor. You don't want that, because you don't want to damage the original object -
Level(Level const &)
is the copy constructor, which is for making a duplicate of an existing object without altering the original.This is exactly what you're asking for, and should be covered pretty early by any competent book in the section on writing classes.
-
for reference, "default constructor" means specifically
Level()
- the constructor with no arguments. This is a well-known term that should also be described in any competent book.
The compiler-generated versions of these constructors are sometimes described as defaulted (and can be requested like
Level(Level const &) = default;
in situations where they wouldn't be generated automatically, or just to make it explicit) - but it's important not to confuse them with the default constructor (which may itself be defaulted if you don't provide one).
Whether the compiler-generated copy constructor will actually do the right thing for you depends entirely on the data members and semantics of your class, which you haven't shown.
In general, it will work as a shallow copy so long as you don't use owning raw pointers or non-copyable types like std::unique_ptr
. The std::shared_ptr
is particularly suitable for automatic shallow copying where you want shared ownership.
If you want a deep copy, you either need to write the copy constructor by hand or use (ie, find or write) a deep-copying smart pointer.
Either way, see the Guidelines on Resource Management for recommendations that will help the compiler generate correct constructors and destructors for you.