shared_ptr (C++0x)

Hi, I was wondering what's the difference between these two:

1
2
3
4
5
6
7
8
triangle::Triangle doIt(void)
{
	point::Point p0 = point::Point(point::ORIGIN); // point::ORIGIN is a const point::Point
	point::Point p1(1,0,0);
	point::Point p2(0,1,0);
	triangle::Triangle tri(std::make_shared<point::Point>(p0), std::make_shared<point::Point>(p1), std::make_shared<point::Point>(p2));
	return tri;
}


and:

1
2
3
4
5
6
7
8
triangle::Triangle doIt(void)
{
	std::shared_ptr<point::Point> p0(new point::Point(point::ORIGIN)); // point::ORIGIN is a const point::Point
	std::shared_ptr<point::Point> p1(new point::Point(1, 0, 0));
	std::shared_ptr<point::Point> p2(new point::Point(0, 1, 0));
	triangle::Triangle tri(p0, p1, p2);
	return tri;
}


In particular, I'm interested in what's happening inside the method doIt, and what happens after the method doIt returns the triangle.

If I understand the way C++ allocates memory correctly, I'm guessing that in the first piece of code the point object gets pushed onto the call stack and the shared_ptr simply points to that address. However, when the function call returns, the call stack gets cleared so the shared_ptr is really pointing to a "bad address". My second guess is that calling std::make_shared() will actually perform the allocation onto the heap for me (if necessary), and the shared_ptr's inside the Triangle object will point to valid resources after doIt() returns.

In the second piece of code, I think that by using the new keyword the point gets allocated onto the heap, and since there's still at least one shared_ptr pointing to that resource it won't be deleted after returning from doIt().

Is my analysis correct? Note that I'm using Visual C++ 2010, which includes some of the new C++0x changes. I believe the new std::shared_ptr functions exactly as boost::shared_ptr does, though I could be incorrect since I've never used either shared_ptr before.

As a last note, are there any debugging tools I can use which will help me identify when a pointer (or reference) points to a valid resource? I know it's good practice to set pointers to NULL when you want to "guarantee" that they don't point to anything useful, but I've found that sometimes even though a resource has been reclaimed the old data still resides at the location and can be manipulated as if it's still there (of course, in the normal operation of the program, this memory will eventually get re-purposed and what seems like a valid object becomes complete garbage).
Last edited on
Topic archived. No new replies allowed.