【发布时间】:2021-06-30 08:43:38
【问题描述】:
所以我认为向矢量添加唯一性是行不通的。 为什么它适用于以下代码? 是不是因为没有将复制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;
}
}
【问题讨论】:
-
为什么你认为你不能制作一个 unique_ptr 的向量?你可以,只要你从不复制这样的指针(你只能移动它们)。
-
我也想知道 'for' 循环是如何引用向量元素的。 — for 循环变量是一个引用。引用不会自行复制/移动任何内容。
标签: c++ unique-ptr push-back