为什么要把临时地址变成非法? [英] Why is taking the address of a temporary illegal?

查看:150
本文介绍了为什么要把临时地址变成非法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道下面写的代码是非法的

I know that the code written below is illegal

void doSomething(std::string *s){}
int main()
{
     doSomething(&std::string("Hello World"));
     return 0;
}

原因是我们不允许获取临时对象的地址。但我的问题是为什么?

The reason is that we are not allowed to take the address of a temporary object. But my question is WHY?

让我们考虑下面的代码:

Let us consider the following code

class empty{};
int main()
{
      empty x = empty(); //most compilers would elide the temporary
      return 0;
}

接受的答案这里提到

通常编译器考虑临时的,并且该副本被构造为位于存储器的完全相同位置中的两个对象,并避免该副本。

"usually the compiler consider the temporary and the copy constructed as two objects that are located in the exact same location of memory and avoid the copy."

根据该语句,可以得出结论:出现在一些内存位置(因此它的地址可能已被采取),编译器决定通过在临时存在的同一位置创建一个就地对象来消除临时。

According to the statement it can be concluded that the temporary was present in some memory location( hence its address could have been taken) and the compiler decided to eliminate the temporary by creating an in-place object at the same location where the temporary was present.

这是否与不能使用临时地址的事实相矛盾?

Does this contradict the fact that the address of a temporary cannot be taken?

我也想知道如何实现返回值优化。有人可以提供与RVO实施相关的链接或文章?

I would also like to know how is return value optimization implemented. Can someone provide a link or an article related to RVO implementation?

推荐答案

&std::string("Hello World")

问题不在于 std :: string(Hello World)生成一个临时对象。问题是表达式 std :: string(Hello World)是引用临时对象的右值表达式。

The problem with this isn't that std::string("Hello World") yields a temporary object. The problem is that the expression std::string("Hello World") is an rvalue expression that refers to a temporary object.

你不能取右值的地址,因为不是所有的值都有地址(而不是所有的值都是对象)。请考虑以下方面:

You cannot take the address of an rvalue because not all rvalues have addresses (and not all rvalues are objects). Consider the following:

42

$ b b

这是一个整数文字,它是一个主表达式和一个右值。它不是一个对象,它(可能)没有地址。 & 42 是无意义的。

This is an integer literal, which is a primary expression and an rvalue. It is not an object, and it (likely) does not have an address. &42 is nonsensical.

是的,右值可能指的是一个对象,第一个例子。问题是,并非所有的值都引用对象。

Yes, an rvalue may refer to an object, as is the case in your first example. The problem is that not all rvalues refer to objects.

这篇关于为什么要把临时地址变成非法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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