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

问题描述 投票:0回答:1

如果在 C++ 的容器中使用可移动但不可复制的类型,例如 unique_ptr, 然后使用依赖于副本的函数,例如复制构造函数、范围插入、运算符 = (&) 或范围分配,在理想的容器实现中会发生什么?

应该:

(a) 代码无法编译

(b) 功能会自动更改为移动类型而不是复制它

(c) 代码抛出异常或 static_assertion

c++ types constructor move-semantics
1个回答
0
投票

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

#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
无法复制。

© www.soinside.com 2019 - 2024. All rights reserved.