Why is taking the address of a temporary illegal?

2020-02-04 19:58发布

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;
}

The accepted answer here mentions

"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?

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

7条回答
手持菜刀,她持情操
2楼-- · 2020-02-04 20:27

It can be taken, but once the temporary ceases to exist, you have a dangling pointer left.

EDIT

For the downvoters:

const std::string &s = std::string("h");
&s;

is legal. s is a reference to a temporary. Hence, a temporary object's address can be taken.

EDIT2

Bound references are aliases to what they are bound to. Hence, a reference to a temporary is another name for that temporary. Hence, the second statement in the paragraph above holds.

OP's question is about temporaries (in terms of the words he uses), and his example is about rvalues. These are two distinct concepts.

查看更多
登录 后发表回答