None of the constructors are called when passing an Anonymous object as an argument

#include <iostream>

struct Box
{
    Box()            { std::cout << "constructor called" << std::endl; }
    Box(const Box&)  { std::cout << "Copy constructor called" << std::endl; }
    Box(Box&&)       { std::cout << "Move constructor called" << std::endl; }
    void run() const { std::cout << "Run" << std::endl;}
};

int main()
{
    Box a(Box());
    a.run();
}

( demo )

In the above code, I was expecting a call Copy Constuctoror Move Constructorwhen passing an anonymous object Box()as an argument. But none of them were called. Probably the reason may be copy elision. But even the constructor is not called for an anonymous object A(). Actually, the above code does not compile and when called run(), the function compiler gave the following error.

a.cpp: In functionint main()’:
a.cpp:28:7: error: request for memberrunina’, which is of non-class typeBox(Box (*)())a.run();

So when we introduce Box a(Box())what happens? What is being created?

+6
source share
1 answer

Most Vexing Parse. - , .

Box a(Box())

- a, Box (*)() Box.

(new in ++ 11) :

Box a{Box{}}

()


MVP stackoverflow : A a (()); ?

, . :

((0));//compiles

, , (CFG) , . , , , .

+15

All Articles