[英]C++ - Return const unique_ptr
I am wondering why I get an error when compiling: 我想知道为什么我在编译时遇到错误:
const std::unique_ptr<int> get() {
return std::make_unique<int>(10);
}
int main() {
const std::unique_ptr<int> value = get();
return EXIT_SUCCESS;
}
I get the following error: 我收到以下错误:
main.cpp: In function ‘int main()’:
main.cpp:10:44: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]’
const std::unique_ptr<int> value = get();
It compiles correctly when I remove const
from the get
signature. 当我从
get
签名中删除const
时,它会正确编译。
Is there any way to return a constant unique_ptr ? 有没有办法返回一个常量unique_ptr?
Because the unique_ptr
is constant it can not be moved only copied. 因为
unique_ptr
是常量,所以只能复制它。 And copying a unique_ptr
is not allowed (otherwise it would not be "unique"). 并且不允许复制
unique_ptr
(否则它将不是“唯一的”)。
If the data pointed to by the pointer should be constant, then use std::unique_ptr<const int>
instead. 如果指针指向的数据应该是常量,那么请改用
std::unique_ptr<const int>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.