问题
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