The return value of the auto_ptr function

I came across such a code.

MyClass MyClass::get_information (const some_datastructure *record) { auto_ptr<MyClass > variable (new MyClass ()); variable ->set_article_id(record->article_id); return *variable.get(); } 

I understand that this returns (a copy?) An object of type MyClass. Initially, I thought that it returns an auto_ptr object, which does not make sense to me (?) Since I thought that the auto_ptr object will be destroyed when it goes beyond the scope.

Anyway, is this the code above? Does the object *variable.get() exist when / after the function returns?

+4
source share
2 answers

since it returns a value, yes, the object is fine, although I don’t understand using a pointer or heap allocation for this question ... It will be easier with a regular variable:

 MyClass var; var.set_article_id(record->article_id); return var; 
+3
source

Yes he does

It actually creates a temporary rvalue of the underlying pointer object, actually a copy. Please note that the return type is not MyClass* , but MyClass . That is why the copy is being returned. *variable.get() also gives the value of r.

+3
source

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


All Articles