I have this problem, there is a function foo()
as follows,
vector<ClassA> vec;
void foo()
{
ClassA a; //inside foo, a ClassA object will be created
a._ptr = new char[10];
vec.push_back(a); //and this newly created ClassA object should be put into vec for later use
}
And AFAIK, vec
will invoke ClassA
's copy-ctor to make a copy of the newly created object a
, and here is the problem. If I define ClassA
's copy-ctor the usual way,
ClassA::ClassA(const ClassA &ra) : _ptr(0)
{
_ptr = ra._ptr;
}
then object a
and its copy (created by vec) will have pointers _ptr
pointing to the same area, when foo
finishes, a
will call the destructor to release _ptr
, then a
's copy in vec
will be a dangling pointer, right? Due to this problem, I want to implement ClassA
's copy-ctor this way,
ClassA::ClassA(ClassA &ra) : _ptr(0) //take non-const reference as parameter
{
std::swap(_ptr, a._ptr);
}
Is my implementation ok? Or any other way can help accomplish the job?
See Question&Answers more detail:os