Reputation: 467
The below code results in run time error. Obviously when unique_ptr
a
goes out of scope it tries to delete the memory which has already been deleted, so causes a heap issue. My question is what changes I should do in Line X as highlighted as they share same memory and there won't be any runtime error either even after using delete
call.
#include <iostream>
#include <memory>
using namespace std;
int main ()
{
int* p = new int (10);
unique_ptr<int> a (p); // Line X
delete p;
return 0;
}
Upvotes: 1
Views: 430
Reputation: 6052
Starting with C++14, your snippet can be fixed as follows:
#include <iostream>
#include <memory>
using namespace std;
int main ()
{
auto a = make_unique<int>(10); // = unique_ptr<int>(new int(10))
return 0;
}
Upvotes: 0
Reputation: 17920
On line X, you're transferring the ownership of the object pointed to by p
to the created unique_ptr<int> a
. You should not explicitly delete it later, otherwise you have a double deletion error.
If you don't want the unique_ptr
to delete the object it points to, you should release it before destruction, e.g:
int main() {
int * p = new int(10);
unique_ptr<int> a(p);
a.release(); // <--- Release ownership of the integer
// unique_ptr a no longer "owns" the integer
delete p;
}
The whole point of unique_ptr
is that it "owns" and object and frees its resources in a RAII manner.
Upvotes: 2