[英]Why can I copy std::unique_ptr into another one without using std::move?
std::unique_ptr shouldn't be copied to another std::unique_ptr unless you use std::move, correct?除非您使用 std::move,否则不应将 std::unique_ptr 复制到另一个 std::unique_ptr,对吗?
But I experience something like this.但我经历过这样的事情。
#include <iostream>
#include <memory>
using namespace std;
class ClassA{
public:
ClassA() {
cout << "created" << endl;
}
~ClassA() {
cout << "destroyed" << endl;
}
void print() {
cout << "ok" << endl;
}
};
void test() {
unique_ptr<ClassA> b(new ClassA());
b->print();
// unique_ptr<ClassA> d(b); this won't compile since you can't copy unique_ptr
ClassA& aa = *b; // ClassA aa = *b; works too.
unique_ptr<ClassA> d(&aa); // but this can, why is that
d->print();
}
int main(int argc, char *argv[])
{
test();
return 0;
}
The program runs ok, Output is:程序运行正常,输出为:
created
ok
ok
destroyed
destroyed
ClassA got destroyed twice, how does this happen? ClassA被销毁了两次,这是怎么回事? Should it crash because of nothing to delete?
它应该因为没有要删除的东西而崩溃吗?
When you do std::unique_ptr<ClassA> d(&aa);
当你做
std::unique_ptr<ClassA> d(&aa);
, you are creating d
using a raw pointer. ,您正在使用原始指针创建
d
。 The unique_ptr
constructor can't see that you are passing it a pointer to an object which is already owned/managed by another std::unique_ptr
. unique_ptr
构造函数看不到您正在向它传递一个指向已由另一个std::unique_ptr
拥有/管理的对象的指针。
Hence the double delete, which causes undefined behavior, ie anything can happen.因此,双重删除会导致未定义的行为,即任何事情都可能发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.