如果参数为 std::format_to 中的输出缓冲区别名,会发生什么?

问题描述 投票:0回答:1

考虑以下示例:

#include <format>
#include <print>

int main() {
    int x = 12345;
    char buffer[32] = "awoo";
    std::format_to(buffer, "{}{}", x, buffer);
    std::println("{}", buffer);
}

此代码预计会输出

12345awoo
,因为我们正在使用参数
{}{}
12345
来格式化
"awoo"

然而,实际输出是

1234512345
。原因很明显:格式化
12345
会写入缓冲区,因此当
buffer
(第二个参数)由
std::format_to
处理时,它不再包含
"awoo"

这就引出了一个问题:根据 C++ 标准的预期结果是什么? https://eel.is/c++draft/format.functions#lib:vformat_to 没有指定之间的别名作为前提条件参数和输出缓冲区是不允许的,所以我不认为这种情况是未定义的行为。

c++ language-lawyer c++23 fmt stdformat
1个回答
1
投票

未明确,

1234512345
12345awoo
都是符合结果。

[format.functions] 中定义的函数使用类模板格式化程序的特化来格式化各个参数。

[format.formatter.spec#1]

因此,每个参数的格式化发生在对其他参数的单独函数调用中。这些调用的顺序没有任何要求,因此副作用彼此之间的顺序不确定。

© www.soinside.com 2019 - 2024. All rights reserved.