Archived

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

A doubt about my copy costructor.

Recommended Posts

BlueChip    100
Hi... In my world, I''ve many trees.... The first tree is created by costructor with the method to load a .X file. Other trees are create by copy costractor like clone of first tree. I use this sintax: MyMesh::MyMesh (MyMesh aMesh) { *this= *aMesh; } This work very well... I save much time if I build many tree ... But in the destructor (where I delete all texture and material) I must put in *link = Null; otherwise I get a run-time error... Now my question is: Can this method give me memory leak?? If yes.... which method I must use? Thanks people!!

Share on other sites
Sneftel    1788
It sounds like you''re describing "reference counting" (albeit in a buggy way). Google for it.

How appropriate. You fight like a cow.

Share on other sites
Guest Anonymous Poster
Usually (pretty mch all the time) you''ll want your copy ctor to look something like this:
MyMesh::MyMesh (const MyMesh& amesh){//bla bla init code}

Also, make sure your assignment operator works fine, since it appears your implementation of the copy ctor uses it...

Share on other sites
BlueChip    100
quote:

It sounds like you''re describing "reference counting"

no... it isn''t a reference counting.
if it it were all the trees would have the same memory, and a change to that memory, it would modify all the trees. I instead can independently move and singolarmnete several the trees...

This is true or I''ve say silly words?

Share on other sites
smart_idiot    1298
It looks like you''re trying to save writing some code by using the = operator in the copy constructor. This should work if
1) All pointers are set to 0 first, since the copy constructor should delete the old data when making a copy to avoid memory leaks.
2) The = operator isn''t virtual. (It probably isn''t.)

Share on other sites
Miserable    606
quote:
Original post by BlueChip
I use this sintax:

MyMesh::MyMesh (MyMesh aMesh)
{
*this= *aMesh;
}

Surely not. You cannot pass an object of class MyMesh to the copy constructor of MyMesh by value! (By-value copies are performed by the copy constructor, which here needs to pass by value and call the copy constructor, which must call the copy constructor ... infinite recursion.) A copy constructor should always be of the form MyMesh::MyMesh(const MyMesh& m).

By the way, you say you "save much time" - compared to what alternative solution? All you do is call the assignment operator, which, unless you wrote your own, will just perform a bit-for-bit copy. If your object contains pointers, that''s usually a bad idea.