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

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

    No, it's against the standard to pass a non-const reference to a temporary object. You can use a const reference:

    class A{};
    
    void bar(const A&);
    
    int main(void)
    {
        bar(A());  // 2
    }
    

    So while some compliers will accept it, and it would work as long as don't use the memory after the semicolon, a conforming compiler will not accept it.

提交回复
热议问题