Author |
Message |
divad12
|
Posted: Tue Apr 01, 2008 10:46 am Post subject: Copying classes with pointers |
|
|
How would I make a deep copy of an object which has properties that are pointers? If I just use the copy operator (=), the pointers would still point to the same memory location.
Essentially I have a class which contains instances of the Node class. The Node class looks something like this:
code: |
class Node
{
public:
vector <Node*> next;
vector <Node*> prev;
/* ... */
};
|
and the class which contains it looks something like this:
code: |
class Circuit
{
public:
vector <Node> gates;
/* ... */
};
|
I wish to copy an instance of the Circuit class, but without having Circuit::gates all point to the same node locations as the original object. Is there a way to do this in C++?
Thanks. |
|
|
|
|
 |
Sponsor Sponsor

|
|
 |
md

|
Posted: Tue Apr 01, 2008 10:59 am Post subject: RE:Copying classes with pointers |
|
|
Overwrite the copy operator and make copies of the data pointed to in your overloaded operator.
Something like c++: | class Circuit
{
public...
Circuit& operator=(const Circuit& to_copy)
{
...
return *this;
}
private:
...
};
|
|
|
|
|
|
 |
divad12
|
Posted: Tue Apr 01, 2008 12:58 pm Post subject: Re: Copying classes with pointers |
|
|
I would have to make new copies of the Node objects, but they contain pointers to each other. If I make new Node objects, they would still point to their older copies. How would I make them point to new copies? Should I use a recursive function? Do I have to completely reconstruct the Circuit? |
|
|
|
|
 |
md

|
Posted: Tue Apr 01, 2008 4:38 pm Post subject: RE:Copying classes with pointers |
|
|
You would have to duplicate the node list, yes. How you do that is entirely up to you. |
|
|
|
|
 |
OneOffDriveByPoster
|
Posted: Wed Apr 02, 2008 12:15 pm Post subject: Re: Copying classes with pointers |
|
|
If am not too sure (especially since the code is not complete), but it looks like you are keeping pointers to things in a vector and I do not think that is safe. Unless if I am mistaken, there is no guarantee that the address of the vector elements will remain the same when you modify the vector. |
|
|
|
|
 |
|