Why is taking the address of a temporary illegal?

前端 未结 7 1904
无人及你
无人及你 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:52

    $5.3.1/2 - "The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue or a qualifiedid."

    Expressions such as

    99
    
    A() // where A is a user defined class with an accessible 
        // and unambiguous default constructor
    

    are all Rvalues.

    $3.10/2 - "An lvalue refers to an object or function. Some rvalue expressions—those of class or cv-qualified class type—also refer to objects.47)"

    And this is my guess: Even though Rvalues may occupy storage (e.g in case of objects), C++ standard does not allow taking their address to maintain uniformity with the built-in types

    Here's something interesting though:

    void f(const double &dbl){
       cout << &dbl;
    }
    
    int main(){
       f(42);
    }
    

    The expression '42' is an Rvalue which is bound to the 'reference to const double' and hence it creates a temporary object of type double. The address of this temporary can be taken inside the function 'f'. But note that inside 'f' this is not really a temporary or a Rvalue. The moment it is given a name such as 'dbl', it is treated as an Lvalue expression inside 'f'.

    Here's something on NRVO (similar)

提交回复
热议问题