gpt4 book ai didi

c++ - 临时参数值何时超出范围?

转载 作者:IT老高 更新时间:2023-10-28 21:56:53 26 4
gpt4 key购买 nike

Possible Duplicate:
Lifetime of temporaries

int LegacyFunction(const char *s) {
// do something with s, like print it to standard output
// this function does NOT retain any pointer to s after it returns.
return strlen(s);
}

std::string ModernFunction() {
// do something that returns a string
return "Hello";
}

LegacyFunction(ModernFunction().c_str());

上面的例子可以很容易地改写为使用智能指针而不是字符串;这两种情况我都遇到过很多次了。无论如何,上面的例子将在 ModernFunction 中构造一个 STL 字符串,返回它,然后在字符串对象中获取一个指向 C 风格字符串的指针,然后将该指针传递给遗留函数。

  1. ModernFunction 返回后存在一个临时字符串对象。什么时候超出范围?
  2. 编译器是否可以调用 c_str(),破坏这个临时字符串对象,然后将一个悬空指针传递给 LegacyFunction? (请记住,字符串对象正在管理 c_str() 返回值指向的内存...)
  3. 如果上面的代码不安全,为什么不安全?有没有比在函数调用时添加临时变量更好、同样简洁的写法?如果它是安全的,为什么?

最佳答案

LegacyFunction(ModernFunction().c_str());

拷贝的销毁将在评估 full expression 之后(即从 LegacyFunction 返回之后)。

n3337 12.2/3

Temporary objects are destroyed as the last stepin evaluating the full-expression (1.9) that (lexically) contains the point where they were created.

n3337 1.9/10

A full-expression is an expression that is not a subexpression of another expression. If a language constructis defined to produce an implicit call of a function, a use of the language construct is considered to be anexpression for the purposes of this definition. A call to a destructor generated at the end of the lifetime ofan object other than a temporary object is an implicit full-expression. Conversions applied to the result ofan expression in order to satisfy the requirements of the language construct in which the expression appearsare also considered to be part of the full-expression.[ Example:

struct S {
S(int i): I(i) { }
int& v() { return I; }
private:
int I;
};
S s1(1); // full-expression is call of S::S(int)
S s2 = 2; // full-expression is call of S::S(int)
void f() {
if (S(3).v()) // full-expression includes lvalue-to-rvalue and
// int to bool conversions, performed before
// temporary is deleted at end of full-expression
{ }
}

关于c++ - 临时参数值何时超出范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12323049/

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