Why doesn't `unique_ptr<QByteArray>` degrade to `QByteArray*`?

夙愿已清 提交于 2019-12-03 01:10:45

问题


I have the following code:

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

  return QDataStream{msg_buf_ptr, QIODevice::WriteOnly};

I am getting the following error:

no known conversion for argument 1 from ‘std::unique_ptr<QByteArray>’ to ‘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?

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


回答1:


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

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.



来源:https://stackoverflow.com/questions/28952141/why-doesnt-unique-ptrqbytearray-degrade-to-qbytearray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!