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

标签 c++ stl

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

FormatMessage API 期望 PTSTRUNICODE 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*那里。而不是 *messagemessage.get() .

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

关于c++ - 取消引用 std::shared_ptr<T[]>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58238987/

相关文章:

c++ - vector 构建的访问冲突

c++ - std::vector 的最大尺寸

c++ - C/C++ PCM开源音频分析仪

c++ - 浮点运算产生的数字本质上为零

c++ - 在 C++ 中使用具有相同类的多个模板

C++ 模板和运算符重载

c++ - 为什么 STL 容器没有虚拟析构函数?

c++ - 使用 STL 的列表对象

c++ - 提供相同的 ostream 和 wostream 流运算符的任何捷径?

c++ - 如何在 vector 中存储单个单词? (c++)