I have the following simple code, and I have not found a thread where smart pointers are used for this simple case, but rather copy objects:
int main()
{
int i = 1;
std::unique_ptr<int> p1(&i);
*p1 = 2;
return 0;
}
This results in _BLOCK_TYPE_IS_INVALID
when the pointer goes out of scope. If I call p1.release()
, the code works fine and I do not get this error. I thought such pointers are smart enough to handle dangling pointers?
An alternative would be if I had a copy of i, which does not give the above error:
std::unique_ptr<int> p1(new int(i));
What is the advantage of using smart pointers here, where I do not want to perform the local copy?
If I were to use a raw pointer:
int i = 1;
int *p1 = &i;
*p1 = 2;
I would not get an error, even if I don't code:
p1 = nullptr;
The answer provided by @qzx is the main reason of the problem you've reported in your code
One additional thing about
std::unique_ptr<>
usage. You should always try to usestd::make_unique<>()
to create astd::unique_ptr
. It sometimes help in using this pointer appropriately by providing appropriate compilation errors.For example, if you change the above code with
std::make_unique<>
asthen most compiler will give error as
It will help you to use a copy which creates a totally new integer whose ownership is taken by
std::unique_ptr<>
This code works.