473,756 Members | 3,566 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Yet Another Question About Smart Pointers (YAQAS)

Hello,

I've been trying to implement smart pointers in C++ (combined with a
reference counter) because I want to do some memory management. My code
is based on the gamedev enginuity articles, various books and ...
whatever I could find on the subject :-)

I'll leave out the reference counter part because its pretty basic, but
my reference counter class is called xObject. My smart pointer class is
called xPointer.

My problem is that I can't figure out how to make my smart pointer
object a pointer. Look at the following code:

--------------- CUT
void test()
{
//xShaderResource is derived from xObject
class xPointer<xShade rResource> myShader2 = new xShaderResource ();
myShader2->loadResource(N ULL); //testing
}
--------------- CUT

This works like a charm. The xShaderResource object will be destroyed in
my garbage collector because myShader2 is beeing destructed after it
goes out of scope when test() returns.

So far so good, but what if let's say I have a vector/list with 1000+
xPointer objects (imagine a resource manager)? They will never go out of
scope, right?

What I need is to do something like this:

--------------- CUT
class xPointer<xShade rResource> *myShader2 = new
xPointer<xShade rResource>(new xShaderResource ());
myShader2->loadResource(N ULL);
--------------- CUT

This should enable me to run through the list and do something like this:

delete (*iterator);

on relevant objects thus forcing them to go away and get collcected. Can
this be done? I kinda figure I need to change/add my operators
somewhere, but I can't figure out how :-(

Can anyone help?

-------------------------------- Relevant code
template<class X>
class xPointer
{
protected:
X* obj;
public:

xPointer()
{
obj = 0;
}

xPointer(X *oP)
{
obj = 0;
*this = oP;
}

~xPointer()
{
if( obj )
obj->Release();
}

X& operator*(void) { return *obj; }

void operator =(X *oP)
{
if( obj )
obj->Release();
obj = oP;
if( obj )
obj->Alloc();
}

void operator =(const xPointer<X> &oP)
{
if( obj )
obj->Release();
obj = oP.obj;
if( obj )
obj->Alloc();
}

X* operator ->(void)
{
return obj;
}
};
Jul 22 '05 #1
6 1804
"Johnny Hansen" <we*******@suxx .dk> wrote in message
news:cj******** **@news.cyberci ty.dk...
Hello,

I've been trying to implement smart pointers in C++ (combined with a
reference counter) because I want to do some memory management. My code
is based on the gamedev enginuity articles, various books and ...
whatever I could find on the subject :-)

I'll leave out the reference counter part because its pretty basic, but
my reference counter class is called xObject. My smart pointer class is
called xPointer.

My problem is that I can't figure out how to make my smart pointer
object a pointer. Look at the following code:

--------------- CUT
void test()
{
//xShaderResource is derived from xObject
class xPointer<xShade rResource> myShader2 = new xShaderResource ();
myShader2->loadResource(N ULL); //testing
}
--------------- CUT

This works like a charm. The xShaderResource object will be destroyed in
my garbage collector because myShader2 is beeing destructed after it
goes out of scope when test() returns.

So far so good, but what if let's say I have a vector/list with 1000+
xPointer objects (imagine a resource manager)? They will never go out of
scope, right?

What I need is to do something like this:

--------------- CUT
class xPointer<xShade rResource> *myShader2 = new
xPointer<xShade rResource>(new xShaderResource ());
myShader2->loadResource(N ULL);
--------------- CUT

This should enable me to run through the list and do something like this:

delete (*iterator);

on relevant objects thus forcing them to go away and get collcected. Can
this be done? I kinda figure I need to change/add my operators
somewhere, but I can't figure out how :-(

Can anyone help?
[...]


Well, first consider using a reference-counted pointer library. If you want
to write your own, then take a look at the FAQ's answers about reference
counting (http://www.parashift.com/c++-faq-lite/ Section 16 items 21 "How do
I do simple reference counting" on), because they contain useful snippets of
code for implementing reference counting.

Now, once you have a working reference-counted smart pointer stored in a
std::list or std::vector, removing elements so that the managed
reference-counted object may be deallocated is about as simple as removing
any other element from the container. A simple example (using std::list)

std::list<smart pointertype>::i terator it = /* something to remove */;
myList.erase( it );

will remove the smart pointer from the std::list, causing the smart
pointer's destructor to be invoked, which will cause the managed object's
reference count to be decreased by one (and deallocated, etc if
appropriate).

--
David Hilsee
Jul 22 '05 #2

"Johnny Hansen" <we*******@suxx .dk> wrote in message
news:cj******** **@news.cyberci ty.dk...
Hello,

I've been trying to implement smart pointers in C++ (combined with a
reference counter) because I want to do some memory management. My code is
based on the gamedev enginuity articles, various books and ... whatever I
could find on the subject :-)

I'll leave out the reference counter part because its pretty basic, but my
reference counter class is called xObject. My smart pointer class is
called xPointer.

My problem is that I can't figure out how to make my smart pointer object
a pointer. Look at the following code:

--------------- CUT
void test()
{
//xShaderResource is derived from xObject
class xPointer<xShade rResource> myShader2 = new xShaderResource ();
myShader2->loadResource(N ULL); //testing
}
--------------- CUT

This works like a charm. The xShaderResource object will be destroyed in
my garbage collector because myShader2 is beeing destructed after it goes
out of scope when test() returns.

So far so good, but what if let's say I have a vector/list with 1000+
xPointer objects (imagine a resource manager)? They will never go out of
scope, right?
Wrong. They will go out of scope when they are removed from the vector or
list, or when the vector or list itself is destroyed.

What I need is to do something like this:

--------------- CUT
class xPointer<xShade rResource> *myShader2 = new
xPointer<xShade rResource>(new xShaderResource ());
myShader2->loadResource(N ULL);
--------------- CUT

This should enable me to run through the list and do something like this:

delete (*iterator);


You are undoing the good work that smart pointers do. You are making life
difficult for yourself by going back to raw pointers. Smart pointers are
more powerful than you realise. You don't need to do any more work. You're
done.

john
Jul 22 '05 #3
John Harrison wrote:
You are undoing the good work that smart pointers do. You are making life
difficult for yourself by going back to raw pointers. Smart pointers are
more powerful than you realise. You don't need to do any more work. You're
done.


I must be missing something, because I can't get it to work. Look at this:

std::vector<xPo inter<xShaderRe source>*> myList;
//defined in global scope for testing purposes
//should be stored in my resource-manager object

------------------ CUT
void test()
{
class xPointer<xShade rResource> myResource = new xShaderResource ();

myList.push_bac k(&myResource) ;
(*myList[0])->loadResource(N ULL);
}
------------------ CUT

When test() returns my "myResource " still gets destructed. I assume its
because the myList only contains a pointer to the local global scope
object, thus will contain a invalid pointer when test() returns. Not good.

However trying to do:
std::vector<xPo inter<xShaderRe source>> myList;

fails miserably. How can I store the actual object in the list, not only
the pointer? This is what I want (i think) :-)


Jul 22 '05 #4

"Johnny Hansen" <we*******@suxx .dk> wrote in message
news:ck******** ***@news.cyberc ity.dk...
John Harrison wrote:
You are undoing the good work that smart pointers do. You are making life difficult for yourself by going back to raw pointers. Smart pointers are
more powerful than you realise. You don't need to do any more work. You're done.
I must be missing something, because I can't get it to work. Look at this:

std::vector<xPo inter<xShaderRe source>*> myList;


Why use smart pointers if you then just go and use ordinary pointers on top?

std::vector<xPo inter<xShaderRe source> > myList;

Now all your problems go away.
//defined in global scope for testing purposes
//should be stored in my resource-manager object

------------------ CUT
void test()
{
class xPointer<xShade rResource> myResource = new xShaderResource ();

myList.push_bac k(&myResource) ;
myList.push_bac k(myResource);
(*myList[0])->loadResource(N ULL);
myList[0]->loadResource(N ULL);
}
------------------ CUT

When test() returns my "myResource " still gets destructed. I assume its
because the myList only contains a pointer to the local global scope
object, thus will contain a invalid pointer when test() returns. Not good.

However trying to do:
std::vector<xPo inter<xShaderRe source>> myList;

fails miserably. How can I store the actual object in the list, not only
the pointer? This is what I want (i think) :-)


If this fails miserably, it must be because your smart pointer is not coded
correctly. How does it fail? Could you post the code.

john
Jul 22 '05 #5
>
If this fails miserably, it must be because your smart pointer is not coded correctly. How does it fail? Could you post the code.


OK, looking at the code you posted earlier, the problem is that you have not
defined a copy constructor for your smart pointer.

Something like this is needed

xPointer(const xPointer<X> &oP)
{
obj = oP.obj;
if( obj )
obj->Alloc();
}

john
Jul 22 '05 #6
John Harrison wrote:
If this fails miserably, it must be because your smart pointer is not

coded
correctly. How does it fail? Could you post the code.

OK, looking at the code you posted earlier, the problem is that you have not
defined a copy constructor for your smart pointer.
Something like this is needed
xPointer(const xPointer<X> &oP)
{
obj = oP.obj;
if( obj )
obj->Alloc();
}


Ahh, I've only done the =copy constructor. It works now! I owe you one,
thanks alot :-)
Jul 22 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
2020
by: cppaddict | last post by:
Hi, I am deleting some objects created by new in my class destructor, and it is causing my application to error at runtime. The code below compiles ok, and also runs fine if I remove the body of the destructor. So I think I am somehow using delete incorrectly, but I'm not sure exaclty what I'm doing wrong. I'd apprecitate any clarification and suggestions for rewriting the below properly.
5
1476
by: Gonçalo Rodrigues | last post by:
Hi all, (note: newbie alert) Suppose you have a hierarchy of objects that you deal with via smart pointers, e.g. something like: template<typename T> class Ref { private:
27
3410
by: Susan Baker | last post by:
Hi, I'm just reading about smart pointers.. I have some existing C code that I would like to provide wrapper classes for. Specifically, I would like to provide wrappers for two stucts defined as ff: typedef struct { float *data ; int count ;
3
1914
by: Vijai Kalyan | last post by:
I have been thinking about this and it may have already been thrashed out and hung out to dry as a topic of no more interest but here goes. I found when implementing a smart pointer that the typical implementation goes like: template<typename T> class SmartPointer { // other stuff
8
5153
by: Axter | last post by:
I normally use a program call Doxygen to document my source code.(http://www.stack.nl/~dimitri/doxygen) This method works great for small and medium size projects, and you can get good documentation like the following: http://axter.com/smartptr Now I'm on a client site, and I'm trying to create the same type of documentation on a very large project. I ran the Doxygen program, and it ran for over 16 hours, before I had
22
10780
by: craig | last post by:
I've declared the following as a "vector" of "lists" using STL vector< list<Edge*> > I've tried many ways to add objects to this but can't figure out how to do it. Does anyone have any tips, or references to material that might explain it? Any help greatly appreciated.
16
4123
by: Yong Hu | last post by:
Does the smart pointer never lead to memory leak? Thanks,
92
5116
by: Jim Langston | last post by:
Someone made the statement in a newsgroup that most C++ programmers use smart pointers. His actual phrase was "most of us" but I really don't think that most C++ programmers use smart pointers, but I just don't know. I don't like them because I don't trust them. I use new and delete on pure pointers instead. Do you use smart pointers?
54
12014
by: Boris | last post by:
I had a 3 hours meeting today with some fellow programmers that are partly not convinced about using smart pointers in C++. Their main concern is a possible performance impact. I've been explaining the advantages of smart pointers endlessly (which are currently used in all our C++ software; we use the Boost smart pointers) as I'm seriously concerned that there is a shift to raw pointers. We are not developing system software but rather...
0
9456
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9275
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10034
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9872
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9713
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7248
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5142
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5304
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3358
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.