取消引用std :: shared_ptr <T []>?

时间:2019-10-04 15:06:26

标签: c++ stl

在波纹管功能中,我需要取消对指向TCHAR数组的共享指针的引用 但是std::share_ptr中可用的操作数似乎都不起作用:

FormatMessage API需要PTSTR,在UNICODE wchar_t*的情况下 如何取消引用给定的指针(请参见代码中的注释)?

如果您认为使用更优雅的sintax可以实现相同的事情,那就太好了,您可以提供示例代码。

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;
}

编辑 感谢答案和建议(使其与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;
}

1 个答案:

答案 0 :(得分:4)

*message返回TCHAR&,而FormatMessage在此处需要TCHAR*。代替*message来做message.get()

此外,由于此函数未保留对格式化消息的引用,因此它应返回std::unique_ptr<TCHAR[]>来记录呼叫者现在是唯一所有者的事实。