为什么在仅一次调用std :: emplace_back的情况下两次调用动作构造函数?

问题描述 投票:0回答:1

我知道std::emplace_back使用new-place在容器提供的位置就地构造元素。

为什么仅在一次调用std::emplace_back时调用两次运动构造函数?

这里是相关代码(检查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));
}
c++ move move-semantics
1个回答
2
投票

您有两个对象;将第二个放在向量上会导致向量调整大小,重新分配内存,因此需要移动。除了emplace_back的就地构造外,这也是移动构造的另一点:为了避免std::vector调整大小时复制昂贵的副本。

将此行添加到代码中时:

elections.reserve(2);

然后您只有一个动作。

© www.soinside.com 2019 - 2024. All rights reserved.