4

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

Wok
  • 4,956
  • 7
  • 42
  • 64
nacho4d
  • 43,720
  • 45
  • 157
  • 240
  • 5
    If you don't have one, consider getting [a good introductory C++ book](http://stackoverflow.com/questions/388242/the-definitive-c++-book-guide-and-list). It is critical to have a good understanding of the memory model and object model when programming in C++. – James McNellis Oct 09 '10 at 07:32
  • 2
    I recognize that memory management is the thing I have to work the most in C++, but is just every time I start reading a book they talk about HOW to program and the GRAMMAR rules and that I already know from other programming languages... If you could suggest a specific book for memory management It would be appreciated ;) – nacho4d Oct 09 '10 at 08:02

3 Answers3

7

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.

Arun
  • 19,750
  • 10
  • 51
  • 60
1

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

Alexander Rafferty
  • 6,134
  • 4
  • 33
  • 55
1

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

JoshD
  • 12,490
  • 3
  • 42
  • 53