views:

70

answers:

3

In order to make a deep copy of myArr,

vector <Point> myArr;

where Point is a class with 2 ints as members,

Do I need to do something special? or is ok with

vector <Point> otherArr = myArr;

I need to delete some points in otherArr but at the same time I need all the points in myArr for later usage.

thanks in advance

+1  A: 

The assignment should be fine. It makes sure that all data is copied over right. Just make sure that Point is copyable.

Alexander Rafferty
How do I make Point copyable? what would happen if is not? thanks ;)
nacho4d
If `Point` is noncopyable, you can't have a `vector<Point>` (in C++03, at least).
James McNellis
A: 

What you have is fine. The vector has an overloaded assignment operator and copy constructor that perform a deep copy.

JoshD
The assignment operator will not be invoked; this is an initialization, not an assignment.
James McNellis
@James McNellis: Thanks :)
JoshD
+2  A: 

See Shallow vs Deep Copies and Effective C++

Point does not need deep copy. As a thumb rule, "deep copy" is required when a class has pointer members. The Point class have only two int members, so it does not require any special effort for "deep copy", the normal or "shallow copy" would do perfectly fine. In fact, it is not required to write a copy-constructor for Point, the default or synthesized one provided by the compiler would do just fine.

Regarding your second question, after the line

vector< Point > otherArr = myArr;

is executed, otherArr and myArr are two independent vectors. Operations (e.g. delete some elements) performed on one of them does not affect the other in any way.

ArunSaha
Thank you for your kind answer and for the links ;) I found they very useful.
nacho4d
@nacho4d: Glad to be of help, you are welcome.
ArunSaha