Declaring an object before initializing it in c++

前端 未结 10 2213
你的背包
你的背包 2020-12-13 17:17

Is it possible to declare a variable in c++ without instantiating it? I want to do something like this:

Animal a;
if( happyDay() ) 
    a( \"puppies\" ); //c         


        
10条回答
  •  猫巷女王i
    2020-12-13 17:24

    Since c++17, there is now an overhead-free way to do this: std::optional. The code in this case would be:

    #include 
    
    std::optional a;
    if(happyDay()) 
        a.emplace("puppies");
    else
        a.emplace("toads");
    

提交回复
热议问题