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

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

    It looked lke it would work, but it did not compile with g++ with the Wall option, here is what I get:

    michael@hardy-lenovo:~/Desktop$ g++ -Wall a.cpp
    a.cpp: In function ‘int main()’:michael@hardy-lenovo:~/Desktop$ g++ -Wall a.cpp
    a.cpp: In function ‘int main()’:
    a.cpp:8: warning: taking address of temporary
    a.cpp:9: error: invalid initialization of non-const reference of type ‘A&’ from a temporary of type ‘A’
    a.cpp:4: error: in passing argument 1 of ‘void bar(A&)’
    michael@hardy-lenovo:~/Desktop$ 
    

    Looks like you will need to use a constant reference.

提交回复
热议问题