Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to initialize reference variables later?

Tags:

c++

Best explained with an example:

Class banana {
    int &yumminess;
    banana::banana() {
        //load up a memory mapped file, create a view
        //the yumminess value is the first thing in the view so
        yumminess = *((int*)view);
    }
}

But that doesn't work :/ there is no way I can know where the view is going to be when I dreclare the "yumminess" reference variable. Right now i just use a pointer and dereference it all the time, is there any way to bring this little extra bit of convenience to my class?

like image 376
Jake Freelander Avatar asked Feb 12 '23 13:02

Jake Freelander


2 Answers

In short: No, it's intentionally not possible.

Think twice: Something like uninitialized references cannot really exist; such wouldn't make sense at all.
Thus they'll need to be set at the time of construction of the enclosing class, or at a point of static initialization.

You'll need to use pointers for such case.


Besides note that

 yumminess = (int*)view;

would be wrongly casted (to a pointer) anyway.


"Right now i just use a pointer and dereference it all the time ..."

That's also easy to overcome writing an appropriate member function to access the reference.

int* yumminess;

// ...

int& yumminessRef() {
    if(!yumminess) { 
        throw some_appropriate_exception("`yumminess` not initialized properly.");
    }
    return *yumminess;
}
like image 99
πάντα ῥεῖ Avatar answered Feb 23 '23 14:02

πάντα ῥεῖ


No, not directly.

If you think the pointer is inconvenient, have a look at std::optional.

like image 29
Christian Hackl Avatar answered Feb 23 '23 13:02

Christian Hackl