Declaring an object before initializing it in c++

前端 未结 10 2205
你的背包
你的背包 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条回答
  •  天命终不由人
    2020-12-13 17:35

    If you want to avoid garbage collection - you could use a smart pointer.

    auto_ptr p_a;
    if ( happyDay() )
        p_a.reset(new Animal( "puppies" ) );
    else
        p_a.reset(new Animal( "toads" ) );
    
    // do stuff with p_a-> whatever.  When p_a goes out of scope, it's deleted.
    

    If you still want to use the . syntax instead of ->, you can do this after the code above:

    Animal& a = *p_a;
    
    // do stuff with a. whatever
    

提交回复
热议问题