在波纹管函数中,我需要取消引用指向 TCHAR
数组的共享指针
然而 std::share_ptr
中可用的操作数似乎都不起作用:
FormatMessage
API 期望 PTSTR
是 UNICODE
wchar_t*
如何取消引用给定的指针(请参阅代码中的注释)?
如果您认为同样的事情可以通过更优雅的语法来实现,那么您提供示例代码会很棒。
const std::shared_ptr<TCHAR[]> FormatErrorMessage(const DWORD& error_code)
{
constexpr short buffer_size = 512;
std::shared_ptr<TCHAR[]> message = std::make_shared<TCHAR[]>(buffer_size);
const DWORD dwChars = FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM,
nullptr,
error_code,
MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
*message, // no operator "*" matches these operands
buffer_size,
nullptr);
return message;
}
编辑 感谢答案和 commnts(唯一)使其与 Microsoft 编译器一起工作的方法是这样的:
const std::shared_ptr<std::array<WCHAR, buffer_size>>
FormatErrorMessageW(const DWORD& error_code, DWORD& dwChars)
{
const std::shared_ptr<std::array<WCHAR, buffer_size>> message =
std::make_shared<std::array<WCHAR, buffer_size>>();
dwChars = FormatMessageW(
FORMAT_MESSAGE_FROM_SYSTEM,
nullptr, // The location of the message definition.
error_code,
MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
message.get()->data(),
buffer_size,
nullptr);
return message;
}
最佳答案
*message
返回 TCHAR&
,而 FormatMessage
需要 TCHAR*
那里。而不是 *message
做 message.get()
.
此外,由于此函数不保留对格式化消息的引用,因此它应该返回 std::unique_ptr<TCHAR[]>
记录调用者现在是唯一所有者这一事实。
关于c++ - 取消引用 std::shared_ptr<T[]>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58238987/