为什么`unique_ptr< QByteArray>`降级为`QByteArray *`? [英] Why doesn't `unique_ptr<QByteArray>` degrade to `QByteArray*`?

查看:139
本文介绍了为什么`unique_ptr< QByteArray>`降级为`QByteArray *`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

  msg_buf_ptr = std::make_unique<QByteArray>();

  return QDataStream{msg_buf_ptr, QIODevice::WriteOnly};

我收到以下错误:

no known conversion for argument 1 from ‘std::unique_ptr<QByteArray>’ to ‘QByteArray*’

但是...为什么?我认为 unique_ptr shared_ptr 在作为参数传递给接受指针的函数时自动降级为裸指针。如果不是,为什么不呢?如果他们(通常)做,为什么在 QByteArray

But...why? I thought unique_ptr and shared_ptr automatically degrade to raw pointers when passed as arguments to functions taking pointers. If not, why not? If they (usually) do, why does this fail in the case of QByteArray?

code> msg_buf_ptr.get(),但似乎应该是不必要的。

I could explicitly call msg_buf_ptr.get(), but that seems like it should be unnecessary.

推荐答案

不,这不是一个特例;标准库智能指针在需要原始指针的上下文中不会隐式地降级。

No, this is not a special case; the standard-library smart pointers do not degrade implicitly in contexts requiring raw pointers.

如问题所述,从 unique_ptr 访问底层原始指针的正确方法是使用 get()。这是一个设计功能,显然旨在帮助避免意外导致多重所有权方案,这将导致未定义的行为。

As mentioned in the question, the proper way to access the underlying raw pointer from a unique_ptr is to use get(). This is a design feature, apparently intended to help avoid accidentally causing multiple-ownership scenarios, which would lead to undefined behavior.

这篇关于为什么`unique_ptr&lt; QByteArray&gt;`降级为`QByteArray *`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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