c++ anonymous constructor doing weird things -
this sample program shows how different constructor called depending on whether pass in local variable, global variable, or anonymous variable. going on here?
std::string globalstr; class aclass{ public: aclass(std::string s){ std::cout << "1-arg constructor" << std::endl; } aclass(){ std::cout << "default constructor" << std::endl; } void puke(){ std::cout << "puke" << std::endl; } }; int main(int argc, char ** argv){ std::string localstr; //aclass(localstr); //this line not compile aclass(globalstr); //prints "default constructor" aclass(""); //prints "1-arg constructor" aclass(std::string("")); //also prints "1-arg constructor" globalstr.puke(); //compiles, though std::string cant puke. }
given can call globalstr.puke()
, i'm guessing calling aclass(globalstr);
, creating local variable named globalstr
of type aclass
being used instead of global globalstr
. calling aclass(localstr);
tries same thing, fails compile because localstr
declared std::string
. possible create anonymous instance of class calling 1-arg constructor non-constant expression? decided type(variablename);
should acceptable way define variable named variablename
?
aclass(localstr); //this line not compile
this tries declare variable of type aclass
named localstr
. syntax terrible, agree, it's way late [changing standard] now.
aclass(globalstr); //prints "default constructor"
this declares 1 called globalstr
. globalstr
variable hides global one.
aclass(""); //prints "1-arg constructor"
this creates temporary object of type aclass
.
aclass(std::string("")); //also prints "1-arg constructor"
this creates temporary.
globalstr.puke(); //compiles, though std::string cant puke.
this uses globalstr
in main
, consistent every other instance of shadowing.
is possible create anonymous instance of class calling 1-arg constructor non-constant expression?
yes, can think of 4 ways:
aclass{localstr}; // c++11 list-initialization, called "uniform initialization" (void)aclass(localstr); // regular "discard result" syntax c. void(aclass(localstr)); // way of writing second line c++. (aclass(localstr)); // parentheses prevent being valid declaration.
as side note, syntax can cause of vexing parse. example, following declares function foo
returns aclass
, 1 parameter localstr
of type std::string
:
aclass foo(std::string(localstr));
indeed it's same rule that's responsible problems - if can parsed valid declaration, must be. why aclass(localstr);
declaration , not statement consisting of lone expression.
Comments
Post a Comment