class X
{
public:
X(){
cout << "X cons called" << endl ;
}
~X(){
cout << "X desc called" << endl ;
}
};
class TimeKeeper {
public:
TimeKeeper(const X& x){};
int get_time(){};
};
int main()
{
X x() ; //這真的夠冤枉 !!!! compile ok , 甚麼都沒做 !!!!!
X x{}; //C++11,C++0x 這樣就行了 !!!
}
今天不小心把 X x 寫成 X x() , 結果竟然 compile 過 執行卻不產生 X 物件 , 查一下才知道原來是 Most vexing parse 問題 ,
想說這語法怎能過關 ?!
TimeKeeper time_keeper( (X()) ); //可以產生想要的結果
TimeKeeper time_keeper( X() ); // 至少 compile 會 error , 有些會 warning !!
參考 :
http://www.parashift.com/c++-faq-lite/empty-parens-in-object-decl.html
http://en.wikipedia.org/wiki/Most_vexing_parse
http://stackoverflow.com/questions/16588750/cs-most-vexing-parse-again
留言列表