Expand scope of a variable initialized in a if/else sequence

后端 未结 3 788
轮回少年
轮回少年 2020-12-07 03:22

I\'m writing a piece of code in which I\'d like to use a different constructor of a class depending on a condition. So far I\'ve used if and else s

3条回答
  •  忘掉有多难
    2020-12-07 04:10

    You can use a smart pointer instead of a direct instance:

    std::unique_ptr my_object;
    
    if (my_boolean) {
         //calling a first constructor
        my_object.reset(new MyClass(arg1));
    }
    else {
        //calling another constructor
        my_object.reset(new MyClass(arg1,arg2));
    }
    //more code using my_object
    

    In contrast to some other solutions proposed here, this will also work for bigger if() {} else if() {} sequences, or switch blocks.


    In case you can't use a compiler capable of the latest standard, you can use the good old std::auto_ptr in the exactly same manner.

    "I tried using the static keyword without success so far."

    Good so! A static variable is certainly not what you want here.

提交回复
热议问题