• Advertisement

Archived

This topic is now archived and is closed to further replies.

This pointer bug is driving me crazy

This topic is 5035 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I''m probably overlooking something stupid or my code is completely messed (very possible due to the lack of sleep I''ve had lately). Anyway, I''m just trying to add a newly created object to my world list. I''m doing:
void CWorldManager::AddObject(CWorldObject *pObject)
{
	pObject->m_iID=GetFreeID();
	WriteToLog("Adding object.");
	m_ObjectList.Add(*pObject);
	WriteToLog("Object Added.");
}
m_ObjectList is just a linked list full of all my objects in the world. I have a model class and then a more complex model inside of that class; the first class is just to make things a whole lot easier (this isn''t my problem, it works fine AFAIK). My problem is that for some reason, one of my pointers inside of that complex class keeps getting set to NULL. For example, if I debug this after I add the object, m_pModel will be 0xfeeefeee (bad pointer). HOWEVER, if I decide to remove
m_ObjectList.Add(*pObject); 
m_pModel ends up being a perfectly suitable location like 0x032f0330. There is no reason at all that this line of code should drastically alter the memory. This is the function that is called:
template<class T>
void CLinkedList<T>::Add(const T Object)
{
	m_List.push_front(Object);
}
m_List is an STL linked list, I just decided to write an easier to use class. I realize this is long and I''m probably doing something really stupid, but that''s why I''m still a beginner :D

Share this post


Link to post
Share on other sites
Advertisement
Problem: You have duplication all over the place. Your CLinkedList<T>::Add method copies its parameter. If the parameter or the original object is subsequently modified, you will see discrepancies. It also means more memory gets used, even if only for a short while.

The real problem is that the duplication invokes the copy constructor, which your probably have no defined. The default copy constructor does a bitwise copy, but sometimes you get shallow copy behavior with that (especially with multiple levels of indirection). I''d recommend providing a copy constructor - or using references.

Share this post


Link to post
Share on other sites
You're right I don't have a copy constructor... fixing that right now.

*Edit*
Oluseyi = teh_win

I usually use references but I wrote that linked list class a while ago and didn't use them much then. The reference cured everything, thanks.

[edited by - Kaezin on May 8, 2004 11:16:57 PM]

Share this post


Link to post
Share on other sites
i agree with Oluseyi who is 100% correct,
but i STRONGLY recomend use of references when possible.

Share this post


Link to post
Share on other sites

  • Advertisement