Let's look at a simple piece of code:
#include <iostream>
#include <memory>
using namespace std;
void Test_smartpointer (Shared_ptr<int> sp)
{
(*SP) + +
;
} void Test_pointer (int *p)
{
(*p) + +
;
} int main ()
{
int n1 = 5, N2 = 5;
Shared_ptr<int> sp (new Int (n1))
Test_smartpointer (sp);
N1=*SP;
Test_pointer (&N2);
cout << "n1 =" << n1 << "n2 =" << n2 << Endl;
return 0;
}
The output is: N1 = 6 N2 = 6
The use of smart pointers is a bit cumbersome, and in the habit of using pointers, the shared_ptr<int> SP (new Int (n1)) can be replaced with shared_ptr<int> sp (&N1).
This will not save the back of the N1=*SP.
The answer is no. Because shared_ptr is automatically freed of the memory it manages, in this code, N1 is the object on the stack and is automatically cleaned up. So the problem is, N1 may be cleaned up two times.
After I found this problem using gcc4.6.3, I used vs and mingw respectively to verify this.
It is strange that the vs2013 community version will not be an error, MinGW also did not complain.
Later I found some of the C++11/14 fully supported online compilers, the result of the direct introduction of the object on the stack after the address of an error.
So be cautious when using Microsoft's compilers or MinGW. Use Gcc/clang in time for confusing code, or online compiler validation.
In addition to the one I used above, the ISO C + + Web site also provides more online compilers.