简体   繁体   中英

dereferencing std::shared_ptr<T[]>?

In bellow function I need to dereference shared pointer to an array of TCHAR however none of the operands available in std::share_ptr seem to work:

The FormatMessage API expects PTSTR which is in case of UNICODE wchar_t* How to dereference the given pointer (see comment in the code)?

If you think the same thing could be achieved with more elegant sintax that it would be great you provide example code.

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

EDIT Thanks to answers and commnts (the only) way to make it work with Microsoft compiler is this:

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 returns TCHAR& , whereas FormatMessage requires TCHAR* there. Instead of *message do message.get() .

Also, since this function doesn't keep a reference to the formatted message, it should return std::unique_ptr<TCHAR[]> to document the fact that the caller is now the sole owner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM