What is the scope of unique_ptr returned by the function?

Will this work correctly? (see example)

unique_ptr<A> source() { return unique_ptr<A>(new A); } void doSomething(A &a) { // ... } void test() { doSomething(*source().get()); // unsafe? // When does the returned unique_ptr go out of scope? } 
+6
source share
3 answers

A unique_ptr returned by the function has no scope because the scope applies only to names.

In your example, the lifetime of the temporary unique_ptr ends at a semicolon. (So ​​yes, this will work correctly.) In general, a temporary object is destroyed when a full expression that lexically contains an rvalue whose evaluation created this temporary object is fully evaluated.

+17
source

Temporary values ​​are destroyed after evaluating the β€œfull expression”, which is the (roughly) largest encompassing expression β€” or in this case, the full expression. So it is safe; unique_ptr is destroyed after doSomething returns.

+3
source

Everything should be fine. Consider

 int Func() { int ret = 5; return ret; } void doSomething(int a) { ... } doSomething(Func()); 

Even though you return ret on the stack, this is normal because it is in the call area.

+1
source

Source: https://habr.com/ru/post/888823/


All Articles