Reputation: 667
Say you had a class in C++ like below:
template<typename T>
class my_class {
public:
private:
std::set<T*> class_set;
int elements_in_set;
}
I'm trying to write a copy constructor for this class, and so far I'm stuck at the following, where I only know how to copy over the integer elements_in_set
, but I'm not sure how to copy over the set, and do a deep copy of the things that other's class_set
's pointers are pointing to:
my_class(my_class const& other)
: class_set{}, elements_in_set{other.elements_in_set} {
//don't know how to copy over the set
}
I know that if the class has a pointer as a member, you'd use new data type[size of data pointer points to]
, but do you have to call new
to make the set itself, and then new
for every pointer in the set? Any help would be greatly appreciated. It would also be nice if there was a way to do this using standard library algorithms rather than for
loops.
Upvotes: 0
Views: 256
Reputation: 555
Depends. Do you want a shallow or a deep copy?
For a shallow copy (both instances of my_class sharing the same T objects) just copy the set in the same way as the int member.
For a deep copy (the new instances gets its own copy of the T objects) you need to run through the original set, create a new T and insert it into the new set. If it is just T objects in the set using new will do the job. If T is a base-class you will have to add a clone function.
Note that having a pointer in a set is at least slightly unusual. If you want the second behaviour (deep copy) using values instead of pointers would give you that for free.
Edit: Note that your int member is redundant. A set keeps track of its size.
Upvotes: 2