Question

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?

Was it helpful?

Solution

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()};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top