gpt4 book ai didi

c++ - 在同一语句中返回传入的临时值并从中读取是否安全?

转载 作者:可可西里 更新时间:2023-11-01 16:36:17 25 4
gpt4 key购买 nike

我只是写了这篇文章,没有想太多。它似乎工作正常,但我不确定它是否绝对安全。

class Foo
{
struct Buffer
{
char data [sizeof ("output will look like this XXXX YYYY ZZZZ")];
};

const char * print (const char * format = DEFUALT_FORMAT, Buffer && buf = Buffer ())
{
sort_of_sprintf_thing (format, buf .data, sizeof (buf.data), ...);
return buf .data;
}
};

std :: cout << Foo () .print ();

所以我认为语义是临时 Buffer 将一直存在,直到整个 cout 语句完成。是这样吗,还是会在此之前超出范围,在这种情况下这是 UB?

最佳答案

是的,您的代码定义明确。

[class.temporary]

3 - [...] Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. [...]

[intro.execution]

11 - [ Note: The evaluation of a full-expression can include the evaluation of subexpressions that are not lexicallypart of the full-expression. For example, subexpressions involved in evaluating default arguments (8.3.6) areconsidered to be created in the expression that calls the function, not the expression that defines the defaultargument. — end note ]

不过,这并不意味着它特别 - 将 Foo().print() 的结果绑定(bind)到 太容易了>char const* 变量,它将在下一个完整表达式中变成悬空指针。

关于c++ - 在同一语句中返回传入的临时值并从中读取是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28280169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com