c++ - Expanded life-span of variables through std::unique_ptr -


with c++11 unique_ptr, object's lifespan seems extended outside of usual scope in following (rather contrived) example:

#include <iostream> #include <memory>  using namespace std;  int main() {     unique_ptr<char> uptr(nullptr);     {         char c = 'x';         cout << "c = " << c << endl;         uptr.reset(&c);         c = 'y';     }     cout << "c = " << *uptr << endl;      return 0; } 

output:
c = x
c = y

the character c, released @ end of scope, survives until end of program. second output 'y', showing unique_ptr not copy value.

is recommended extend lifespan of variable in way?
safe, or carry same dangers reference?

with c++11 unique_ptr, object's lifespan can extended outside of usual scope

no, can't.

the character c, released @ end of scope, survives until end of program.

no doesn't, survives until end of scope, normal.

the second output 'y', showing unique_ptr not copy value.

you're right, unique_ptr not copy value points to. output here irrelevant, because code has undefined behavior when dereference pointer, because thing points no longer exists. code has undefined behavior again when unique_ptr destroyed, , calls delete on location (although can provide no-op deleter).

is recommended extend lifespan of variable in way? safe...

clearly no , no.

or carry same dangers reference?

yes, similar returning reference local variable function. it's more similar having dangling pointer , dereferencing it, addition delete called on location dose of undefined behavior.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -