c++ - 用 iota 初始化一个 unique_ptr 的容器

标签 c++ c++11 unique-ptr iota

为了了解 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});

这显然失败了。原因:

  • 虽然我标记了threemove作为&&这可能不足以将初始值复制/移动到容器中。
  • ++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/

相关文章:

c++ - 具有智能指针的非虚拟删除器

c++ - 为什么 C2662 错误不适用于对 std::unique_ptr<B> 对象的常量引用?

c++ - 如何在 Constructor 中编辑 2D vector

c++ - 具有共享指针的列表的共享指针

C++11 std::copy 内部函数

c++ - map 的 std::for_each() 给出无效的初始化错误

c++ - 如何使此模板 typedef 在 C++11 中有效?

c++ - 在类<std::unique_ptr<B>> 中强制模板函数为 T=B*

c++ - 向 gtest 测试用例添加延迟

c++ - 无法初始化数组