Saturday, 31 August 2013

Does move semantic unsuitable to the array in C++11?

Does move semantic unsuitable to the array in C++11?

I test the unique_ptr<> as follow
#include <iostream>
#include <memory>
using namespace std;
class A
{
public:
virtual ~A() {}
virtual void print()
{
cout << "A::Print()" << endl;
}
};
class B : public A
{
public:
virtual ~B() {}
virtual void print()
{
cout << "B::Print()" << endl;
}
};
int main()
{
A a;
B b;
A* arr[2] = {&a, &b};
arr[0]->print();
arr[1]->print();
unique_ptr<A*[]> ptr(move(arr));
/*
unique_ptr<A*[]> ptr(new A*[2]{&a, &b});
*/
ptr[0]->print();
ptr[1]->print();
return 0;
}
It get the result like (g++ 4.7.3)
A::Print()
B::Print()
A::Print()
B::Print()
Aborted (core dumped)
It seem like the ptr and arr point to the samething and when call
destructor, it has been deleted twice.
Why the move semantic don't take effect here?
Does it unsuitable to the array or it is about the unique_ptr?

No comments:

Post a Comment