I am writing a sparse matrix class. I need to have a node class, which will be a template for its contents. My issue in writing this class is:
How do I store the contents?
I want to store the contents by value. If I stored it by pointer and it should be destroyed, then I’d have trouble. How can I safely perform a copy in the setContents method? Does C++ offer any guarantees that a class that should be placed into my node container has the capability to clone itself?
I’ve looked into the copy constructor, but I have some qualms. What if the contained class does not implement a copy constructor? Then passing it to the node by reference would not be wise, since that could lead to a dangling reference if the original object should be deleted or go out of scope.
What is the sort of “standard C++” way of doing this?
The standard C++ approach is to mandate that the type(s) used by your container class must be copyable (and perhaps assignable). It is a very reasonable requirement and is used by all of the container class templates in the standard library.
For built-in types and simple POD-types, a user-declared copy constructor typically isn’t needed. A writer of a class that isn’t as simple but needs to have value sematics will typically have had to provide a suitable copy constructor in any case.