When you want to pass a resource from your function, then there are two cases: either the resource is copyable (it has accessible copy constructor) or not.
If the resource is copyable (e.g. shared_ptr
), then you can simply copy it to wherever it needs to go and you're done. When your function returns, it's only your copy of the resource that's destroyed.
If the resource is not copyable (e.g. unique_ptr
), then you need to move it, which is what the move semantics in C++ 11 is all about.
When you move the resource to a new location, the old location becomes empty, so when its destructor is called, there is nothing to do.
If you're passing the resource using return
, then you don't need to do anything special, return
moves automatically if it can.
For example:
std::unique_ptr<resource> get_resource()
{
std::unique_ptr<resource> result(new resource());
if (result->is_something_wrong())
{
throw std::exception();
}
return result;
}
If you want to pass the resource to a field, or something like that, then you need to explicitly say that you want to move it by using std::move
:
class resource_user
{
void init_resource()
{
std::unique_ptr<resource> result(new resource());
if (result->is_something_wrong())
{
throw std::exception();
}
resource_ = std::move(result);
}
std::unique_ptr<resource> resource_;
};