copy constructor for objects with vectors

Hi -

I have an object with a couple of vectors in it:

1
2
3
4
5
6
class MyClass
{
private:
	Mod*	pMod;
	std::vector<SocReg>	regI;
	std::vector<SocReg>	regQ;


(SocReg is another class I've defined.)

For the copy constructor, do I have to run a loop to copy each element of the vectors, or is there a shorthand way to do it?

Thanks.
According to http://www.cplusplus.com/reference/stl/vector/operator=/ you just called the operator = for the source vector.
So, this would do it, then?

1
2
3
4
5
MyClass::MyClass(const Myclass &mc) // copy constructor
	: pMod(mc.pMod),
	  regI(mc.regI),
	  regQ(mc.regQ)
{}
I believe so!
Assuming you just want to copy the pointer and not that data pointed to, yes.
No, I want to make a copy of the data. New pointers and everything. What's the right way to accomplish that?

Thanks.
closed account (DSLq5Di1)
1
2
3
4
5
MyClass::MyClass(const Myclass &mc) // copy constructor
	: pMod(new Mod(*mc.pMod)),
	  regI(mc.regI),
	  regQ(mc.regQ)
{}
I wasn't precise enough in my response to firedraco above.

pMod is a true pointer, and can (and should) contain the same address as mc.pMod. So, I think line 2 in sloppy's answer is inaccurate.

But, for the arrays (vectors) regI and regQ, I do indeed want new vectors created. Will lines 3 and 4 in sloppy's answer accomplish that?

Sorry for the confusion.
No, you will need to manually step through and deep copy all the pointers in each vector.

EDIT: wait.... your vectors don't have pointers. So nevermind. SocReg is not a pointer, so the contained object will be copied in full just fine.

sloppy's suggestion will work.
Last edited on
So...vectors are "smart" enough that they'll do a full copy in an copy constructor initialization?
Yes.
pMod(mc.pMod) is a shallow copy. Both pointers points to the same address (to the same object)
pMod( mc.pMod->clone() ) is a depth copy. A new object is created. The objects could be considered 'equal' (not the 'same'), the pointers point to different address.
ne555: I believe that is the desired behavior in this case. This program contains multiple levels of data objects. The variable pMod is a back-pointer to an object that contains an object of MyClass. In the (unlikely) event that the containing class ever has more than one object of MyClass, they should point to the same place. It could probably be static, as far as that goes.

It's really, *really* unlikely that this constructor will ever be called, as the program only calls for a single instance of this object, but I just like to have them correct, just in case.
Topic archived. No new replies allowed.