Reputation: 43427
This example is in the context of iOS, but the principle applies elsewhere...
// global variable...
std::unique_ptr<Foo> global_foo_handle;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// use Obj-C to compute a valid path string
const char * path = [[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithUTF8String: "file.txt"]] UTF8String];
// Only now can I call the ctor of my foo.
global_foo_handle = std::move(std::unique_ptr<Foo>(new Foo(path)));
}
This doesn't really look all that sane to me. Is there no cleaner way? I see that the only valid unique_ptr operator =
are move assignments. I suppose it's clear enough what's being done here. It also seems like I can omit the std::move
so long as the ephemeral unique_ptr
made for the newly allocated Foo remains a temporary rather than being made into an lvalue.
I guess I'm sort of wondering why there isn't an operator= that takes a pointer to T
? That way we skip the creation of the temporary unique_ptr.
Upvotes: 0
Views: 116
Reputation: 28349
You do not need the std::move
...
global_foo_handle = std::unique_ptr<Foo>(new Foo(path));
Or you can just reset the value...
global_foo_handle.reset(new Foo(path));
However, you must understand that the deleter is part of the unique_ptr type, and any pointer assigned to the unique_ptr via reset
will be deleted by the deleter of the original unique_ptr object.
Upvotes: 2
Reputation: 59997
Use reset method to achieve this - See http://www.cplusplus.com/reference/memory/unique_ptr/reset/
Upvotes: 1