In order to assign a new value to a std::unique_ptr
use the reset()
method.
However, a big word of caution regarding the use of this method is that the std::unique_ptr
object will try to dispose of the managed pointer by invoking a Deleter
function on the managed pointer when the std::unique_ptr
object will be being destroyed or when the managed pointer will be being replaced by another value.
The default Deleter
calls the delete
operator with the managed pointer.
That being said, if the std::unique_ptr
is used with its default Deleter
, the pointer assigned to the std::unique_ptr
using the reset()
method must point to a memory previously obtained from a call to the new
operator. Otherwise, undefined behavior will result.
#include <iostream>
#include <memory>
int main()
{
std::unique_ptr<int> u_ptr;
int * p = new int(100);
u_ptr.reset(p);
std::cout << *u_ptr << '\n'; // outputs 100
// u_ptr goes out of scope and calls delete(p); Memory is properly deallocated.
}
But, it's possible to use a Deleter
function that does nothing and in this case it will be safe to assign the value of any pointer to the std::unique_ptr
. However, in this case care needs to be taken to ensure that the pointer stored in the std::unique_ptr
does not outlive the object where it points to. Such usage of the unique pointer could be counterintuitive:
#include <iostream>
#include <memory>
struct fake_deleter
{
void operator()(int *){}
};
int main()
{
std::unique_ptr<int, fake_deleter> u_ptr;
int n = 100;
u_ptr.reset(&n);
std::cout << *u_ptr << '\n'; // outputs 100
/* u_ptr goes out of scope and calls fake_deleter(&n);
which does nothing. This is correct in this example */
}
char*
in your smart pointer you are declaring it wrong. It should bestd::unique_ptr<char> char_ptr;
– Bitch