Why is taking the address of a temporary illegal?

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

    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.

提交回复
热议问题