为什么这段代码允许push_backunique_ptr做向量?

所以我认为向 vector 添加 unique 不应该起作用。为什么它适用于以下代码?是不是因为没有将复制 ctor 设置为“已删除”?

#include <iostream>
#include <vector>
#include <memory>

class Test
{
    public:
        int i = 5;
};


int main()
{
    std::vector<std::unique_ptr<Test>> tests;
    tests.push_back(std::make_unique<Test>());
    
    for (auto &test : tests)
    {
        std::cout << test->i << std::endl;
    }

    for (auto &test : tests)
    {
        std::cout << test->i << std::endl;
    }
}

回答

这里没有副本,只有移动。

在这种情况下,make_unique 将生成一个未命名的唯一指针实例,并且此 push_back 将其视为一个 r 值引用,它可以根据需要使用。

它产生的结果与此代码几乎相同:

std::vector<std::unique_ptr<Test>> tests;
auto ptr = std::make_unique<Test>();
tests.push_back(std::move(ptr));

如果您想搜索有关此问题的更多信息,这称为移动语义。(这仅适用于 c++11 及更高版本)


以上是为什么这段代码允许push_backunique_ptr做向量?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>