Declare a reference and initialize later?

后端 未结 10 2103
遥遥无期
遥遥无期 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:46

    You need to initliaze it. But if you would like to conditionally initialize it, you can do something like this:

    MyObject& ref = (condition) ? MyObject([something]) : MyObject([something else]);
    
    0 讨论(0)
  • 2020-12-01 06:48

    AFAIK this can't be done with a reference. You'd have to use a pointer:

    MyClass *ptr;
    
    if (condition)
        ptr = &object;
    else
        ptr = &other_object;
    

    The pointer will act similar to a reference. Just don't forget to use -> for member access.

    0 讨论(0)
  • 2020-12-01 06:50

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

    std::shared_ptr<ObjType> pObj;
    if(condition)
        pObj = std::make_shared<ObjType>(args_to_constructor_1);
    else
        pObj = std::make_shared<ObjType>(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.

    0 讨论(0)
  • 2020-12-01 06:51

    In C++, you can't declare a reference without initialization. You must initialize it.

    0 讨论(0)
提交回复
热议问题