Copy a class into another with list of pointers
-
Hi,
Suppose i have a class and i have defined it in stack.MyClass class;
when i copy this class into another:
class = anotherClass;
will the pointers which i have defined it in the object will copy or not?
I have a list of pointers in my class and i just want to copy my object into another object,
so i want to copy list of pointers too. I want to for example if i delete these pointers from original class, then the copied don't change.more infor: myClass is not type of QObject
-
You like to copy one instance of a class into another instance of the same class?
For example this case
@
class MyClass {
...
};...
Myclass A;
MyClass B;
...
A = B;
...
@
or
@
class MyClassA {
...
};
class MyClassB {
...
};...
MyclassA A;
MyClassB B;
...
A = B;
...
@In the first case it depends. With the standard copy constructor probably yes. With your implementation of the copy constructor it depends what you are doing-
In case the second you have to implement an assignment operator anyway yourself.
-
Watch out, on the one hand you say
"will the pointers which i have defined it in the object will copy or not? "
and then
"if i delete these pointers from original class, then the copied don’t change."But those contradict each other.
Either you copy the pointers, then they point to the same object and one pointer will become a dangling pointer once the object is deleted (e.g. via the other pointer). So if the second class tries to access the object, the program is aborted with a segfault.
Or you copy the instances, but then the pointers will be different, because after the copy there will be two independent instances at distinct memory locations.
You probably want the second mechanism and that is not the default (copy constructor) behaviour. Normally, it just copies everything by value, including pointer values, i.e. the number a pointer actually is. It will not call the copy constructor on the objects that the pointer points to (and that's good because the program can't know what that pointer really means and whether it's valid at all.)
So you need to implement your own copy constructor and assignment operator, to do the deep copying manually, cloning instances and setting new pointers in the copy target appropriately. -
Thanks Emanual :) ;)