Why is taking the address of a temporary illegal?

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

    Long answer:

    [...] it can be concluded that the temporary was present in some memory location

    By definition:

    • "temporary" stands for: temporary object
    • an object occupies a region of storage
    • all objects have an address

    So it doesn't take a very elaborate proof to show that a temporary has an address. This is by definition.

    OTOH, you are not just fetching the address, you are using the builtin address-of operator. The specification of the builtin address-of operator says that you must have a lvalue:

    • &std::string() is ill-formed because std::string() is a rvalue. At runtime, this evaluation of this expression creates a temporary object as a side-effect, and the expression yield a rvalue that refers to the object created.
    • &(std::string() = "Hello World") is well-formed because std::string() = "Hello World" is a lvalue. By definition, a lvalue refers to an object. The object this lvalue refers to is the exact same temporary

    Short answer:

    This is the rule. It doesn't need the (incorrect, unsound) justifications some people are making up.

提交回复
热议问题