要了解C ++ 11的复杂性,我正在玩unique_ptr
一些。
我想知道,有什么方法可以iota
用来初始化的容器unique_ptr
吗?
我首先使用了独特的无ptr的解决方案,该解决方案运行良好:
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++
。还是还有其他障碍?
为了以98个实例结束unique_ptr
,必须有98个对的调用new
。您尝试只逃脱一种-不可能飞翔。
如果您真的有意将方钉砸入一个圆孔中,则可以执行以下操作:
#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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句