使用 std::format_args 解决范围后堆栈使用问题

Jon*_*ler 3 c++ address-sanitizer c++20 stdformat

std::format_args当我尝试与 一起使用时,出现 stack-use-after-scope 错误std::vformat()。重现它的简单代码是:

#include <format>
#include <iostream>
#include <string>

int main() {
    int i = 42;
    std::string s = "hello";
    std::format_args args = std::make_format_args(i, s);
    std::cout << std::vformat("Number: {}, Word: {}", args) << '\n';

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的i和s变量应该仍然在范围内并且不是右值,所以我不确定是什么触发了错误。如果我删除并直接在调用中args调用to ,一切都会按预期进行。我缺少什么?std::make_format_args()std::vformat()

这是我编译上述代码的命令:clang++-17 --std=c++23 -stdlib=libc++ -fsanitize=address fmt.cpp。

S.M*_*.M. 8

std::make_format_args(i, s);不归std::format_args args。未指定类型的结果可以隐式转换为std::format_args args在返回的临时对象中保留对某些内部状态的悬空引用。

正确的用法是:

auto args = std::make_format_args(i, s);
Run Code Online (Sandbox Code Playgroud)

https://godbolt.org/z/Tozs7a9bP

更好的用法是:

std::cout << std::vformat("Number: {}, Word: {}", std::make_format_args(i, s)) << '\n';
Run Code Online (Sandbox Code Playgroud)