c++ - None of the constructors are called on passing Anonymous Object as 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 above code expecting either copy constuctor
or move constructor
called on passing anonymous object box()
argument. none of them called. reason might copy elision
. constructor not called anonymous object a()
. actually, above code not compile , on calling run()
function compiler gave following error.
a.cpp: in function ‘int main()’: a.cpp:28:7: error: request member ‘run’ in ‘a’, of non-class type ‘box(box (*)())’ a.run();
so when type box a(box())
happening? being created?
this case of most vexing parse. when parsed function declaration, is.
box a(box())
is declaration of function named a
taking function of type box (*)()
argument , returning box
.
a solution use (new in c++11) aggregate initialization constructing objects:
box a{box{}}
(demo)
the mvp discussed in simplest form in stackoverflow question most vexing parse: why doesn't a(()); work?
if have expression within valid. example:
((0));//compiles
to learn more how languages defined, , how compilers work, should learn formal language theory or more context free grammars (cfg) , related material finite state machines. if interested in though wikipedia pages won't enough, you'll have book.
Comments
Post a Comment