dimanche 4 octobre 2020

Does emplace_back construct an object in its new location instead of using a move?

From this link it states

For example, in the code that we began with, my_vec.push_back("foo") constructs a temporary string from the string literal, and then moves that string into the container, whereas my_vec.emplace_back("foo") just constructs the string directly in the container, avoiding the extra move. For more expensive types, this may be a reason to use emplace_back() instead of push_back(), despite the readability and safety costs, but then again it may not. Very often the performance difference just won’t matter

So I decided to try that and this is what i did

class foo
{
    public:
    int counter;
    foo()
    {
        std::cout << "Regular constructor\n";
    }
    foo(const foo& f)
    {
        std::cout << "Copy constructor\n";
    }
    foo(foo&& f)
    {
        std::cout << "Move constructor\n";
    }
};

int main()
{
   std::vector<foo> f;
   f.push_back(foo()); //Regular constructor and Move Constructor
   f.emplace_back(foo()); //Regular constructor and Move Constructor
}

I noticed that both push_back and emplace_back behave similarly. I was thinking that emplace_back will only be calling the regular constructor based on what I read since it will be constructed in the vector stack.

Aucun commentaire:

Enregistrer un commentaire