Jump to content
  • Advertisement
Sign in to follow this  
BloodLust666

pointers

This topic is 4306 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 have an instance where i need to take a pointer, create a new pointer using "new" and copy the values from the passed pointer into the new one so the old one can be deleted and the new one will retain the values from the old one.

Share this post


Link to post
Share on other sites
Advertisement
What you described is usually referred to as 'cloning.' It's a common idiom in C++.

You have to write a clone() member function yourself. Yuo can sometime leverage the copy constructor.

Share this post


Link to post
Share on other sites
A _very_ important thing to remember is that if your class has member variables which are pointers, those variables will also have to be copy-constructed.

-me

Share this post


Link to post
Share on other sites
Quote:
Original post by EvilKnuckles666
so i would have to create my own copy constructor and copy constructor those pointers as well?


correct. if you just assign the values of the member variable pointers then you're just copying a memory address, not the data itself. So you'll have to implement copy-constructors for all the member variable objects also. If they're dynamically allocated arrays, you'll have to new [] and then memcpy the data, etc.

-me

Share this post


Link to post
Share on other sites
The "deep copy" issue is one of the most problamatic in all of programming, because there is no such thing as a "correct" one-size-fits-all solution.

But for your case I think you want to implement either the "deepest copy reasonable" / "copy everything I can create" version or the "copy everything I own" version. I would start with the "copy everything I own" version.

Which simply means this, every single thing you destroy in your destructur, you should create a new copy instance of in your assignment operator and copy constructor.

So if you destructor does this:

delete x;
// or something like this:
x.Dispose();
x = null;

in your copy functions you should use:

x = new XsType(*(rhs.x));

not:

x = rhs.x;

Share this post


Link to post
Share on other sites
what's wrong with this code? it's giving me an error


myClass(myClass &Copy)
{
m_pOne = NULL;
m_pTwo = NULL;

memcpy((void*)m_pOne , (void*)Copy.m_pOne, sizeof(myClass));
memcpy((void*)m_pTwo , (void*)Copy.m_pTwo, sizeof(myClass));
m_Three= Copy.m_Three;
};

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!