Initializing a std::unique_ptr by passing the address of the pointer

Somewhere under the covers, unique_ptr<foo> has a data member of type foo*.

However, it’s not legitimate for a user of the class to directly modify that data member. Doing so would not necessarily preserve the class invariants of unique_ptr, in particular it wouldn’t free the old pointer value (if any). In your special case you don’t need that to happen, because the previous value is 0, but in general it should happen.

For that reason unique_ptr doesn’t provide access to the data member, only to a copy of its value (via get() and operator->). You can’t get a foo** out of your unique_ptr.

You could instead write:

foo *tmp;
init_foo(&tmp);
std::unique_ptr<foo, custom_deleter> foo_ptr(tmp);

This is exception-safe for the same reason that std::unique_ptr<foo, custom_deleter> foo_ptr(new foo()); is exception-safe: unique_ptr guarantees that whatever you pass in to its constructor will eventually get deleted using the deleter.

Btw, doesn’t custom_deleter need an operator()(foo*)? Or have I missed something?

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)