xkimi
xkimi

Reputation: 39

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?

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? Should it crash because of nothing to delete?

Upvotes: 1

Views: 218

Answers (1)

AVH
AVH

Reputation: 11516

When you do std::unique_ptr<ClassA> d(&aa);, you are creating d using a raw pointer. 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.

Hence the double delete, which causes undefined behavior, i.e. anything can happen.

Upvotes: 6

Related Questions