Why doesn't `unique_ptr` degrade t

2019-03-07 04:36发布

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条回答
2楼-- · 2019-03-07 04:41

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.

查看更多
登录 后发表回答