问题
I have allocated a pointer with new operator and assigned the ownership of the memory to a new unique_ptr . Do I have to delete the pointer allocated using new? Is there a memory leak here?
#include <iostream>
#include <memory>
using namespace std;
int main()
{
int *a = new int;
*a = 5;
std::unique_ptr<int> auptr;
auptr.reset(a);
int *b = auptr.get();
cout << *b << endl;
cout << *a << endl;
return 0;
}
回答1:
When your code reaches return
, you have three pointers (a
, auptr
and b
) pointing at the same object, which was allocated by new
. After return auptr
will go out of scope and it's destructor will deallocate the object, so you don't have to do it manually and there are no memory leaks.
Just note that your code looks as misuse of unique_ptr
. You make a raw pointer initially, and get another raw pointer from an intermediate smart pointer. Consider using std::make_unique and get rid of raw pointers.
回答2:
No. unique_ptr
has the ownership now and its gets deallocated when it goes out of scope.
回答3:
The ownership has been transferred to the unique_ptr
auptr
and deallocation is now the responsibility of the unique_ptr
.
You can test whether the memory that is allocated is also being de-allocated with some modifications to your program.
#include <iostream>
#include <memory>
struct Int {
Int() { std::cout << "Int...\n"; }
~Int() { std::cout << "~Int...\n"; }
};
struct D {
void operator() (Int* p) {
std::cout << "Calling delete for Int object... \n";
std::cout << "Deleting at " << p << '\n';
delete p;
}
};
int main()
{
std::cout << "Creating new Int...\n";
Int* i = new Int();
std::cout << "Created at " << i << '\n';
std::unique_ptr<Int, D> UPInt;
UPInt.reset(i);
}
Output:
Creating new Int...
Int...
Created at 0x234ec30
Calling delete for Int object...
Deleting at 0x234ec30
~Int...
You can see that the object created at a certain location is also being deleted.
See DEMO
来源:https://stackoverflow.com/questions/54414334/transferring-ownership-of-raw-pointer-to-unique-ptr