简体   繁体   English

为什么移动构造函数被调用两次,而 std::emplace_back 只被调用一次?

[英]Why is movement constructor invoked twice while std::emplace_back is called only once?

I understand that std::emplace_back uses placement-new to construct the element in-place at the location provided by the container.我知道std::emplace_back使用placement-new 在容器提供的位置就地构造元素。

Why is movement constructor invoked twice while std::emplace_back is called only once?为什么移动构造函数被调用两次,而std::emplace_back只被调用一次?

Here is the related code(check https://godbolt.org/z/-NXzNY ):这是相关代码(检查https://godbolt.org/z/-NXzNY ):

#include <vector>
#include <string>
#include <iostream>

struct President
{
    std::string name;
    std::string country;
    int year;

    President(std::string p_name, std::string p_country, int p_year)
        : name(std::move(p_name)), country(std::move(p_country)), year(p_year)
    {
        std::cout << "I am being constructed.\n";
    }
    President(President&& other)
        : name(std::move(other.name)), country(std::move(other.country)), year(other.year)
    {
        std::cout << "I am being moved.\n";
    }
    President& operator=(const President& other) = default;
};

int main()
{
    std::vector<President> elections;
    std::cout << "emplace_back:\n";
    elections.emplace_back("Nelson Mandela", "South Africa", 1994);

    President pst("Franklin", "the USA", 1936);

    std::cout << "=====================" << std::endl;
    elections.emplace_back(std::move(pst));
}

You have two objects;你有两个对象; Putting the second to the vector causes a vector resize, memory reallocation, hence the movement requirement.将第二个放入向量会导致向量调整大小,memory 重新分配,因此需要移动。 In addition to construction-in-place that emplace_back does, that's another point of the move construction: To avoid expensive copies when std::vector resizes.除了emplace_back所做的就地构造之外,这是移动构造的另一点:在std::vector调整大小时避免昂贵的副本。

When adding this line to your code:将此行添加到您的代码时:

elections.reserve(2);

Then you have only one movement.那么你只有一个动作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM