-2

我测试 unique_ptr<> 如下

#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;
}

它得到类似 (g++ 4.7.3) 的结果

A::Print()
B::Print()
A::Print()
B::Print()
Aborted (core dumped)

看起来ptrandarr指向相同的东西,当调用析构函数时,它已被删除两次。

为什么移动语义在这里不起作用?

它不适合数组还是与unique_ptr有关?

4

2 回答 2

4

The problem here is that unique_ptr<T> assumes that the object it manages was allocated with new. Since it is statically allocated on the stack instead, the unique_ptr destructor crashes when it tries to delete your array.

I'm not sure what you're trying to achieve with this unique_ptr anyways. Unique pointers make sure that the managed object is deleted at the end of the scope, but arrays allocated on the stack are deleted at the end of the scope, inherently. Would you have no unique_ptr, your code would function the same and not leak anyways.

于 2013-09-01T03:14:18.130 回答
3

The problem here is that you have no dynamically allocated memory here (never use the new keyword). So the unique_ptr is trying to free memory (call delete on) that was never allocated. My suggestion try to write simpler code, because you do a ton of things that are very unconventional.

  1. You store A* for no reason, they will be delete automatically, I can't think of any good reason to store them as pointers
  2. You don't use any standard library containers, you could use a std::array<A,2> instead of a c-style array
  3. Also I'm guessing you just made this as a test so I can't really tell what your trying to achieve here
于 2013-09-01T03:14:51.857 回答