为了了解 C++11 的复杂性,我正在研究 unique_ptr
有一点。
我想知道,有什么办法可以使用iota
吗?初始化 unique_ptr
的容器?
我从 unique-ptr-less 解决方案开始,效果很好:
std::vector<int> nums(98); // 98 x 0
std::iota(begin(nums), end(alleZahlen), 3); // 3..100
现在让我们尽可能地使用unique_ptr
std::vector<std::unique_ptr<int>> nums(98); // 98 x nullptr
std::unique_ptr three{ new int{3} };
std::iota(begin(nums), end(nums), std::move{three});
这显然失败了。原因:
- 虽然我标记了
three
与move
作为&&
这可能不足以将初始值复制/移动到容器中。 -
++initValue
也不会工作,因为initValue
类型为unique_ptr<int>
, 并且没有operator++
定义。但是:我们可以定义一个自由函数unique_ptr<int> operator++(const unique_ptr<int>&);
这至少会解决这个问题。 - 但是在
unique_ptr
中再次不允许复制/移动该操作的结果。这次我看不出如何欺骗编译器使用move
.
好吧,这就是我停下来的地方。我想知道我是否错过了一些有趣的想法,关于如何告诉编译器他可能 move
operator++
的结果.还是还有其他障碍?
最佳答案
为了结束 unique_ptr
的 98 个实例,必须调用 98 次 new
。你试图逃脱一个 - 它不可能飞。
如果你真的想把一个方形的钉子敲成一个圆孔,你可以做 something like this :
#include <algorithm>
#include <iostream>
#include <memory>
#include <vector>
class MakeIntPtr {
public:
explicit MakeIntPtr(int v) : value_(v) {}
operator std::unique_ptr<int>() {
return std::unique_ptr<int>(new int(value_));
}
MakeIntPtr& operator++() { ++value_; return *this; }
private:
int value_;
};
int main() {
std::vector<std::unique_ptr<int>> nums(98);
std::iota(begin(nums), end(nums), MakeIntPtr(3));
std::cout << *nums[0] << ' ' << *nums[1] << ' ' << *nums[2];
return 0;
}
关于c++ - 用 iota 初始化一个 unique_ptr 的容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23581361/