Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - dynamically use either reference or local variable

Tags:

c++

reference

I would like to do something like this (I'm aware that this won't compile):

struct Container{
    vector<int> storage;
};

float foo(Container* aContainer){
    if(aContainer!=NULL)
        vector<int>& workingStorage=aContainer->storage;
    else
        vector<int> workingStorage; 


    workingStorage.reserve(1000000);
    ....use workingStorage to calculate something......

    return calculated_result;
}

So - if i pass a Container to the function, i want that the function uses the vector in the container to work with instead of a local variable. If no container is provided, it should use a local variable.

of course I could just in the end of the function copy the local variable to the storage of the Container, but that's not what I want to do.

Thanks!

like image 564
Mat Avatar asked Dec 01 '22 04:12

Mat


1 Answers

Create a local std::vector<int> named local_storage for the case where a container is not provided by the caller, then create a reference to whatever container you are actually going to use.

std::vector<int> local_storage;

std::vector<int>& working_storage = aContainer 
                                        ? aContainer->storage 
                                        : local_storage;
like image 128
James McNellis Avatar answered Dec 03 '22 16:12

James McNellis