简体   繁体   English

为什么我可以在不使用 std::move 的情况下将 std::unique_ptr 复制到另一个?

[英]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.

相关问题 为什么不使用 std::move 就不能在结构化绑定后返回 std::unique_ptr? - Why can't std::unique_ptr be returned after structured binding without using std::move? 你能从一个 std::vector 复制 Derived Class 对象吗<std::unique_ptr<baseclass> &gt; 到另一个 std::vector <std::unique_ptr<baseclass> &gt;? </std::unique_ptr<baseclass></std::unique_ptr<baseclass> - Can you copy Derived Class objects from one std::vector<std::unique_ptr<BaseClass>> to another std::vector<std::unique_ptr<BaseClass>>? 为什么我不能在C ++ 14中移动lambda中的std :: unique_ptr? - Why can't I move the std::unique_ptr inside lambda in C++14? 用std :: move初始化std :: unique_ptr - Initialize std::unique_ptr with std::move 为什么list <unique_ptr>中的unique_ptr的std :: move()没有真正移动它? - Why doesn't std::move() of unique_ptr from list<unique_ptr> really move it? 使用std :: move将unique_ptr移到向量中 - using std::move to move a unique_ptr into a vector std::move 在 unique_ptr 和它拥有的另一个之间 - std::move between unique_ptr and another that it owns 无法移动时无法从函数返回std :: unique_ptr - Cannot return std::unique_ptr from function without move 使用std :: unique_ptr的std :: vector - using an std::vector of std::unique_ptr 使用std :: unique_ptr和std :: istream吗? - Using std::unique_ptr with std::istream?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM