Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ multiple unique pointers from same raw pointer

Consider my code below. My understanding of unique pointers was that only one unique pointer can be used to reference one variable or object. In my code I have more than one unique_ptr accessing the same variable.

It's obviously not the correct way to use smart pointers i know, in that the pointer should have complete ownership from creation. But still, why is this valid and not having a compilation error? Thanks.

#include <iostream>
#include <memory>

using namespace std;

int main()
{
    int val = 0;
    int* valPtr = &val;

    unique_ptr <int> uniquePtr1(valPtr);
    unique_ptr <int> uniquePtr2(valPtr);

    *uniquePtr1 = 10;
    *uniquePtr2 = 20;

    return 0;
}
like image 302
Engineer999 Avatar asked Mar 17 '18 10:03

Engineer999


People also ask

Can two unique pointers point to same address?

Pointers: Pointing to the Same AddressThere is no limit on the number of pointers that can hold (and therefore point to) the same address.

Can unique pointer be copied?

A unique_ptr does not share its pointer. It cannot be copied to another unique_ptr , passed by value to a function, or used in any C++ Standard Library algorithm that requires copies to be made. A unique_ptr can only be moved.

Can you use smart pointers and raw pointers in the same program?

C++ Standard Library smart pointers have a get member function for this purpose, and CComPtr has a public p class member. By providing direct access to the underlying pointer, you can use the smart pointer to manage memory in your own code and still pass the raw pointer to code that does not support smart pointers.

What is the difference between shared pointer and unique pointer?

Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.


1 Answers

But still, why is this valid

It is not valid! It's undefined behaviour, because the destructor of std::unique_ptr will free an object with automatic storage duration.

Practically, your program tries to destroy the int object three times. First through uniquePtr2, then through uniquePtr1, and then through val itself.

and not having a compilation error?

Because such errors are not generally detectable at compile time:

unique_ptr <int> uniquePtr1(valPtr);
unique_ptr <int> uniquePtr2(function_with_runtime_input());

In this example, function_with_runtime_input() may perform a lot of complicated runtime operations which eventually return a pointer to the same object valPtr points to.


If you use std::unique_ptr correctly, then you will almost always use std::make_unique, which prevents such errors.

like image 89
Christian Hackl Avatar answered Sep 24 '22 23:09

Christian Hackl