I am currently optimising my code and I have a question regarding the std::vector
I have a class MyClass which I have rewritten the copy/move constructor and their corresponding operators.
MyClass(const std::string& id, int x);
MyClass(const MyClass& other);
MyClass(MyClass&& other);
~MyClass();
MyClass& operator=(const MyClass& other);
MyClass& opratror*(MyClass&& other);
I created a vector and tried the following
std::vector<MyClass> vec;
MyClass a("A", 1);
vec.push_back(a); //#1
vec.emplace_back("B", 2); //#2
vec.push_back(MyClass("C", 3)); //#3
in #1 the copy constructor is called (which I know vector store by values so it copies a) in #2 it saves a copy constructor call only calls the constructor in #3 it calls the constructor and move constructor
But what I found is that, at #2, #3 where the vector is not empty, every push back / emplace / emplace_back triggers the copy/destroy of existing items.
in #2, it copies "A" and destroyed the existing "A" in #3, it does the same to "A" and "B"
it seems the vector resorts all the items whenever the array changes. Does it mean that using a class vector could make things inefficient? Is that the best solution to use a vector storing pointers so that there's not copies / destructors calls during resorting, only pointer copying?
Thanks
noexcept
. – Kerrek SBstd::vector::reserve
. – songyuanyao