As the following code presents, I tried to delete the object by the raw pointer get from a unique_ptr. But, as the output shows, the complier reported errors. However, for raw pointers, we can do this int *p1 = new int{100}; int* p2 = p1; delete p2;
.
Besides, I thought that unique_ptr maintain its ownership by move semantics. As the get() function of unique_ptr returns the raw pointer, how does the unique_ptr can still have the ownership of the object. Meanwhile, why the raw pointer doesn't get the ownership. At the same time, I am confusing how does this implemented. Thanks.
#include <iostream>
#include <memory>
int main(int argc, char const *argv[])
{
std::unique_ptr<int> newPtr = std::make_unique<int>(1234);
std::cout << *newPtr << std::endl;
int* rawInt = newPtr.get();
*rawInt = 200;
delete rawInt;
rawInt = nullptr;
std::cout << *newPtr << std::endl;
return 0;
}
The code was performed on MacOs and the output is: