srinath29 srinath29 - 10 days ago 5
C++ Question

unique_ptr is going out of scope within a struct

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

#include<iostream>
#include<memory>
#include<vector>

struct un{
int i;
};

struct un2{
int i;

void testTheUN(){
temp->i=1000;
}

void main2(){
un u;
temp = std::unique_ptr<un>(&u);
std::cout<<temp->i<<"\n";
testTheUN();

}
private:
std::unique_ptr<un> temp;
};


int main(){


un2 u;
u.main2();


}


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

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


so in
un2::main2()
function the temp got initialized and got assigned some value. Then when I am calling the
testTheUN()
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
main2()
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

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.

Use

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

instead.