C ++-返回const unique_ptr [英] C++ - Return const unique_ptr

查看:67
本文介绍了C ++-返回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;
}

我收到以下错误:

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();

当我从中删除 const 时,它可以正确编译 get 签名。

It compiles correctly when I remove const from the get signature.

有什么方法可以返回常量unique_ptr吗?

Is there any way to return a constant unique_ptr ?

推荐答案

由于 unique_ptr 是常量,因此只能复制而不能移动。并且不允许复制 unique_ptr (否则将不是唯一)。

Because the unique_ptr is constant it can not be moved only copied. And copying a unique_ptr is not allowed (otherwise it would not be "unique").

如果数据指向指针所指向的值应该是常量,然后使用 std :: unique_ptr< const int> 代替。

If the data pointed to by the pointer should be constant, then use std::unique_ptr<const int> instead.

这篇关于C ++-返回const unique_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆