Search code examples
c++vectorstduser-defined-types

User Defined types and std::vector in C++


I am trying to create a vector of 2D points in C++. My question is whether I need to define the copy constructor, the assignment operator and a default constructor for the 2D point before I use the std::vector to store the points? Also, how do I overload operators/ make member functions for the vector that is defined in the std library? Thanks for your help :)


Solution

  • User-defined types need good copying semantics always. This is true even when you are not putting them into vectors. What it means to copy one object to another varies, but clearly one requirement is that doing so shouldn't crash the program. So the real question is whether your user defined type has good copying semantics or not. Obviously without seeing the type it is hard to say.

    If you have a simple type like struct Point { int x, y; }; then that already has good copying semantics and you don't need to do anything more. Same applies if your class contains other objects that themselves have good copying semantics, so there's no problem if you wanted to include a std::string in your type, e.g. struct NamedPoint { std::string name; int x, y; };

    Usually the problem arises when the class has to do something in the destructor such as delete some memory. Then you need to write an assignment operator and copy constructor.

    Much more detail can be found here.

    PS that discussion you linked was somewhat confused.