Implementation for header file
main.cpp
#include <iostream>
#include <vector>
#include "Person.h"
using namespace std;
int main()
{
vector<Person> test{};
test.push_back (Person{ "Chinese", 16 });
test.push_back(Person{});
return 0;
}
Person.h
#pragma once
#include <iostream>
class Person
{
public:
std::string* ethnicity ;
int age;
Person(std::string ethnicity = "Caucasian", int age = 15);
~Person();
Person(const Person& source);
Person (Person&& source) noexcept;
};
Person.cpp
#include "Person.h"
Person :: Person(std::string ethnicity, int age)
: age(age)
{ this->ethnicity = new std::string;
*this->ethnicity = ethnicity;
}
Person :: Person(const Person& source): Person (*source.ethnicity, source.age)
{
std::cout << "Copy constructor deep called!" << std::endl;
}
Person :: Person(Person&& source) noexcept: ethnicity(source.ethnicity), age(source.age)
{
std::cout << "Move constructor called!" << std::endl;
source.ethnicity = nullptr;
}
Person :: ~Person()
{
if (this->ethnicity != nullptr)
std::cout << "Destructor called!" << std::endl;
else
std::cout << "Destructor called for nullptr!" << std::endl; delete ethnicity;
}
From my understanding, only 2 move constructors should be called. But why are 3 move constructors called? The first pushback should create a temporary object through the constructor, and then the move constructor will be called, then the destructor would be called for the temporary object. The process would be the same for the 2nd pushback, so in total there would only be 2 move constructors getting called. But why are there 3?
>Solution :
But why are there 3?
When std::vector needs more space it copies/moves all the elements from the old area to the new area.
Solution 1
To minimise this, call(or use) std::vector::reserve member function before pushing many elements onto the vector. This pre-allocates the needed space.
vector<Person> test{};
test.reserve(2);
test.push_back(Person{"Chinese", 16});
test.push_back(Pserson{});
Solution 2
Or you can create the vector to be of particular size like:
vector<Persion> test(2);
test.push_back(Person{"Chinese", 16});
test.push_back(Pserson{});