metablaster
metablaster

Reputation: 2184

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

Upvotes: 1

Views: 231

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136247

*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.

Upvotes: 4

Related Questions