如果你在C++中使用一个只移动类型的容器的复制构造函数,会发生什么?[已关闭]

70gysomp  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(62)

已关闭,此问题为opinion-based。它目前不接受回答。
**想改善这个问题吗?**更新问题,以便editing this post可以用事实和引用来回答。

关闭7天前。
此帖子5天前编辑并提交审核,未能重新打开帖子:
原始关闭原因未解决
Improve this question
如果在C++中的容器中使用一个可移动但不可复制的类型(如unique_ptr),那么使用一个依赖于复制的函数(如复制构造函数,范围插入,运算符=(&)或范围赋值),在理想的容器实现中应该发生什么,为什么?
应:
(a)代码无法编译
(b)这些函数会自动更改为移动文字,而不是复制文字
(c)代码抛出异常或static_assertion

a0x5cqrl

a0x5cqrl1#

最简单的方法就是尝试一下。考虑一下如果我们尝试下面的程序会发生什么。

#include <vector>
#include <memory>
#include <algorithm>

int main() {
    std::vector<std::unique_ptr<int>> vec = { 
      std::make_unique<int>(1), 
      std::make_unique<int>(2) 
    };
    std::vector<std::unique_ptr<int>> vec2;

    std::copy(
      vec.begin(), vec.end(),
      std::back_inserter(vec2)
    );
}

代码无法编译,因为std::unique_ptr无法复制。

相关问题