문제

Given

struct A
{
    void a(void) { std::cout << "A" << std::endl; }
};

const A &a = A(); /* Make a copy of A and bind to a */
const A &b(A());  /* Does nothing */

a.a(); /* Prints A */
b.a(); /* Error, same as if b doesn't exist */

Why does the second form of "bind temporary to const reference" seem to be equivalent to a no-op?

도움이 되었습니까?

해결책

This is just another case of most vexing parse, you're declaring a function rather than a const reference to A.

You could fix this by using C++11 uniform initialization:

const A &b{A()};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top