Use of the shared_ptr of C++11 Smart Pointers (1) __c++

Source: Internet
Author: User

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.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.