by thrownaway2424 · 11y ago · 0 comments
std::unique_ptr<BigObject> Blerg(yourmom) {
std::unique_ptr<BigObject> big_object_ptr;
BigObject foo, bar;
if (2 > yourmom) {
big_object_ptr.reset(foo);
} else {
big_object_ptr.reset(bar);
}
return std::move(big_object_ptr);
}
This isn't valid code but it's pretty close.Unfortunately this comes at a cost. Most notably, now you're unnecessarily stressing the allocator. But worse, you no longer enjoy the benefits of value semantics [1].
[1] https://akrzemi1.wordpress.com/2012/02/03/value-semantics/
big_object_ptr.reset(...)
will cause the BigObject copy constructor to be called. The object pointed to by unique_ptr does not have the same storage as the objects "foo" and "bar". At the very least, you need to do big_object_ptr.reset(std::move(foo));
which will cause foo to be moved into the unique_ptr's storage.In code like this, you should just use make_unique, in which case the BigObject is constructed in place, and unique_ptr can be RVO'ed:
if (...) {
return make_unique<BigObject>(...);
} else ...