The following code creates a temporary object A and pushes it into a vector. The copy constructor is deleted and the move constructor is called during the push_back. I am not sure the design of this code is correct, and surely there is a memory leak.
using namespace std;
class A
{
public:
A(const string& str)
{
ptr = new char[str.size()];
copy(str.begin(), str.end(), ptr);
cout << ptr << " Constructor\n" ;
}
A(const A& a) = delete; // copy constructor
A( A&& a)
{
cout << "Move constructor\n";
ptr = a.ptr;
a.ptr = nullptr;
}
~A()
{
cout << ptr << " Destructor\n";
delete[] ptr;
ptr = nullptr;
}
void print()
{
cout << ptr << endl;
}
private:
char* ptr;
};
int main()
{
vector<A> v;
v.reserve(5);
v.push_back( A("hello") );
v[0].print();
cout << "here" << endl;
return 0;
}
The output is:
hello Constructor
Move constructor
Why the print function doesn't print, and the destructor is not called? Thanks
Aucun commentaire:
Enregistrer un commentaire