gpt4 book ai didi

c++11 - 您可以使用初始化列表中的 unique_ptr 来初始化 STL 容器吗?

转载 作者:行者123 更新时间:2023-12-02 22:38:13 29 4
gpt4 key购买 nike

我就想知道这个问题。考虑一下:

#include <iostream>
#include <map>
#include <memory>

int main() {
std::map< int, std::unique_ptr<int> > m =
{ { 1, std::unique_ptr<int>(new int(3)) } };

return(0);
}

这是 C++11。它无法在 GCC 上编译并出现大量错误消息,其中包括一条

/usr/include/c++/4.9/ext/new_allocator.h:120:4: error: use of deleted function ‘constexpr std::pair<_T1, _T2>::pair(const std::pair<_T1, _T2>&) [with _T1 = const int; _T2 = std::unique_ptr<int>]’
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }

是否有可能做我在这里想做的事情?我注意到使用shared_ptr,它工作正常。是否可以使用 unique_ptr 来做到这一点?如果是这样,我错过了什么?如果没有,为什么不呢?

最佳答案

没有。

initializer_list 的元素无法修改。

unique_ptr 无法移动(因为它是 const),也无法复制(因为它是只能移动的类型),所以你完蛋了。

关于c++11 - 您可以使用初始化列表中的 unique_ptr 来初始化 STL 容器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38427160/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com