srinath29 srinath29 - 9 months ago 37
C++ Question

unique_ptr is going out of scope within a struct

my code is this and in a file called uniqueptr_scope.cpp


struct un{
int i;

struct un2{
int i;

void testTheUN(){

void main2(){
un u;
temp = std::unique_ptr<un>(&u);

std::unique_ptr<un> temp;

int main(){

un2 u;


I compiled with this
g++ -std=c++1y uniqueptr_scope.cpp

Coming to my question:
I wanted to check the scope a unique pointer within a class or struct. But when I am running the code, I am getting output as

*** Error in `./a.out': free(): invalid pointer: 0x00007fffd9328e40 ***
Aborted (core dumped)

so in
function the temp got initialized and got assigned some value. Then when I am calling the
the unique_ptr is going out of scope. As I have created a class level unique_ptr , the scope should be of the class by default.

Suppose the unique_ptr's scope is of
even then the main2 has not exited completely and thereby unique_ptr's destructor shouldn't be called!
That's what I am confused!

note: using g++ 4.8 compiler (Which is latest in Ubuntu repo) so had to give the "c++1y" std

Answer Source

After the lines

un u;
temp = std::unique_ptr<un>(&u);

temp is a unique_ptr that points to &u. After the function returns, the pointer under temp is a dangling pointer.


un u;
temp = std::make_unique<un>(u);