Why is taking the address of a temporary illegal?

前端 未结 7 1884
无人及你
无人及你 2020-12-03 08:24

I know that the code written below is illegal

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


        
7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 08:32

    &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
    

    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.

提交回复
热议问题