Question about smart pointers. (scoped_ptr)

Actually I'm studying those smart pointers. But I'm having a question.

Having this code,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include "stdafx.h"
#include <iostream>
#include <boost/shared_ptr.hpp>

#include <boost/scoped_ptr.hpp>

using std::cin;
using std::cout;
using std::endl;

class SampleClass
{
public:
	SampleClass()
	{
	
	}
	~SampleClass()
	{

	}

	void Print()
	{
		cout<<"Hella World"<<endl;
	}
};

void UsePtr(SampleClass* ptr)
{
	boost::scoped_ptr<SampleClass> SamplePtr(new SampleClass());
	ptr = SamplePtr.get();
	ptr->Print();
}

int _tmain(int argc, _TCHAR* argv[])
{
	SampleClass* ptr = NULL;

	UsePtr(ptr);	

	ptr->Print();
	
	cin.get();

	return 0;
}


Inside _tmain
After UsePtr(ptr);
Why ptr->Print(); Succeeds?

We are allocating that smart pointer in the stack inside
1
2
3
4
5
6
void UsePtr(SampleClass* ptr)
{
	boost::scoped_ptr<SampleClass> SamplePtr(new SampleClass());
	ptr = SamplePtr.get();
	ptr->Print();
}


Wouldn't there be a memory leak since "SamplePtr" is being destroyed out of scope?

Thanks in advance, hoping for an answer, I'm new to this weird world of Smart Pointers, and I want to be smarter than them :D
Last edited on
UserPtr's parameter "ptr" is passed by value and has no affect on "ptr" inside of main. It succeeds because you got lucky - Print() didn't need to access *this for anything, so it never dereferenced a null pointer. However that's not guaranteed. This has nothing to do with smart pointers:

Works: http://ideone.com/VlJ14r
Segfaults: http://ideone.com/GRFW7h
Last edited on
D: Ok!, it was weird, It never happened before to access a method that did not need to access *this when setting the pointer to NULL. Merely coincidence it was coded in this case.

It is a bit confusing, but I guess I should investigate a little more, later on.

Thanks.
Last edited on
Topic archived. No new replies allowed.