临时参数值何时超出范围? [英] When do temporary parameter values go out of scope?

查看:54
本文介绍了临时参数值何时超出范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
临时人员的生存期

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样式的字符串的指针,然后将该指针传递给旧函数.

The above example could easily be rewritten to use smart pointers instead of strings; I've encountered both of these situations many times. Anyway, the above example will construct an STL string in ModernFunction, return it, then get a pointer to a C-style string inside of the string object, and then pass that pointer to the legacy function.

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

推荐答案

LegacyFunction(ModernFunction().c_str());

销毁将在评估完整表达式之后(即从 LegacyFunction 返回之后).

Destruction of copy will be after evaluation of full expression (i.e. after return from LegacyFunction).

n3337 12.2/3

临时对象被销毁为最后一步在评估全表达式(1.9)时(按词法)包含创建它们的点.

n3337 12.2/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.

n3337 1.9/10

全表达式是不是另一个表达式的子表达式的表达式.如果是语言构造被定义为产生一个函数的隐式调用,使用该语言构造被认为是一个出于此定义的目的而使用的表达式.对析构函数的调用是在的生命周期结束时生成的除临时对象之外的其他对象是隐式完整表达式.转换应用于的结果为了满足出现该表达式的语言结构的要求而创建的表达式也被认为是完整表达式的一部分.[示例:

n3337 1.9/10

A full-expression is an expression that is not a subexpression of another expression. If a language construct is defined to produce an implicit call of a function, a use of the language construct is considered to be an expression for the purposes of this definition. A call to a destructor generated at the end of the lifetime of an object other than a temporary object is an implicit full-expression. Conversions applied to the result of an expression in order to satisfy the requirements of the language construct in which the expression appears are 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
{ }
}

这篇关于临时参数值何时超出范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆