Is it legal to pass a newly constructed object by reference to a function?

后端 未结 9 2139
刺人心
刺人心 2020-12-31 04:44

Specifically, is the following legal C++?

class A{};

void foo(A*);
void bar(const A&);

int main(void)
{
    foo(&A());  // 1
    bar(A());  // 2
}

It a

9条回答
  •  再見小時候
    2020-12-31 05:32

    foo is not allowed in fully standard compliant C++, whereas bar is okay. Though chances are, foo will compile with warning, and bar may or may not compile with a warning as well.

    A() create a temporary object, which unless bound to a reference (as is the case in bar), or used to initialize a named object, is destroyed at the end of the full expression in which it was created. A temporary created to hold a reference initializer persists until the end of its reference's scope. For the case of bar, that's the function call, so you can use A inside bar perfectly safely. It is forbidden to bound a temporary object (which is a rvalue) to a non-const reference. It is similarly forbidden to take the address of a rvalue (to pass as argument to initialize A for foo).

提交回复
热议问题