Declare a reference and initialize later?

后端 未结 10 2136
遥遥无期
遥遥无期 2020-12-01 05:58

I have a reference to MyOjbect, but the the exact object depends on a condition. So I want to do something like this:

MyObject& ref; 
if([co         


        
10条回答
  •  借酒劲吻你
    2020-12-01 06:50

    I usually do this (C++ 11 or later):

    std::shared_ptr pObj;
    if(condition)
        pObj = std::make_shared(args_to_constructor_1);
    else
        pObj = std::make_shared(args_to_constructor_2);
    

    which is clean and allows using object definition with (possibly different) constructions, a thing you can't do directly with pointers as the compiler will complain from using temporary objects.

提交回复
热议问题