临时对象,函数参数和隐式转换 [英] temporary object, function parameters and implicit cast

查看:165
本文介绍了临时对象,函数参数和隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下情形中:

  struct Foo 
{
// ...
operator Bar(){...} //隐式转换为bar
}

Foo GetFoo(){...}
void CallMeBar(Bar x){ ...}

// ...
CallMeBar(GetFoo());

修改cast操作符,
$ b

GetFoo 返回类型为Foo的临时对象。此对象是否存活直到CallMe返回?标准说了什么?



我明白如果 CallMe 会接受Foo,临时对象不会被销毁直到 CallMe 返回。我不知道,然而,隐式转换改变这,只有临时 Bar 被保证存活。






典型的情况是Foo = CString,Bar = char *由Foo保存(和释放)的数据。

解决方案

无论是什么类型的转换,临时对象都会调用 CallMe ()函数因为C ++标准:



12.2.3 [...]临时对象作为最后一步(词法)包含它们被创建的点的fullexpression(1.9)。 [...]



1.9.12一个表达式不是另一个表达式的子表达式。


In the following scenario:

struct Foo
{
   // ...
   operator Bar() {... }  // implicit cast to Bar
}

Foo GetFoo() { ... }
void CallMeBar(Bar x) { ... }

// ...
CallMeBar( GetFoo() );

[edit] fixed the cast operator, d'oh[/edit]

GetFoo returns a temporary object of Type Foo. Does this object survive until after CallMe returns? What does the standard say?

I understand that if CallMe would accept Foo, the temporary object would not be destroyed until after CallMe returns. I am not sure, however, fi the implicit cast changes this, and only the temporary Bar is guaranteed to survive.


A typical case would be Foo = CString, Bar = char *, i.e. Bar referencing data held by (and freed by) Foo.

解决方案

Regardless of the cast, the temporary object(s) will "survive" the call to CallMe() function because of the C++ standard:

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

1.9.12 A fullexpression is an expression that is not a subexpression of another expression.

这篇关于临时对象,函数参数和隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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