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

后端 未结 9 2154
刺人心
刺人心 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:29

    Those A objects will only exist until execution reaches the semicolon. So, the calls are safe, but don't try to save the pointer and use it later. Also, the compiler may require bar take a const reference.

提交回复
热议问题