#include <memory>
class bar{};
void foo(bar &object){
std::unique_ptr<bar> pointer = &object;
}
I want to assign an address of the object to the pointer. The above code obviously wont compile, because the right side of the assignment operator needs to be a std::unique_ptr. I've already tried this:
pointer = std::make_unique<bar>(object)
But it throws many errors during compilation. How can I do that?
Update
As said in the answers - using the std::unique_ptr::reset
method led to undefined behaviour. Now I know, that in such cases I should use a standard pointer.
void foo(bar &object){
std::unique_ptr<bar> pointer;
pointer.reset(&object);
}
But be aware this is not recommended, you should not create a unique_ptr
to a reference that is being passed to a function. At the end of the function, when pointer
is being destroyed it will try to destroy object
as well, and it won't be available outside the function call, resulting in an access memory error.
Example: This will compile, but give a runtime error.
struct bar{ int num;};
void foo(bar &object){
std::unique_ptr<bar> pointer;
pointer.reset(&object);
}
int main()
{
bar obj;
foo(obj);
obj.num; // obj is not a valid reference any more.
return 0;
}
On the other hand you might want to consider using shared_ptr this can help you to decide: unique_ptr or shared_ptr?.