Devesh Agrawal
Devesh Agrawal

Reputation: 9212

How to assign address of a int variable to unique_ptr

This is the code.

int main()
{
    unique_ptr <int> p {nullptr};
    int val = 100;
    p = &val;   // Not working  - compilation error
    p = move(&val);   // Not working  - compilation error
    cout << *p;
    return 0;

}

What is the correct way?

Upvotes: 0

Views: 153

Answers (2)

flogram_dev
flogram_dev

Reputation: 42888

Only dynamically allocated objects should be assigned to unique_ptrs, because the unique_ptr may try to delete the object.

As for the actual question, the reset() function of unique_ptr is used to reassign the pointer.

Upvotes: 3

Jon
Jon

Reputation: 437854

With unique_ptr::reset:

p.reset(&val);

Of course in this particular case this will result in undefined behavior when p goes out of scope and it tries to delete the int, but that's another matter.

Upvotes: 1

Related Questions