C++ – dynamically use either reference or local variable – Education Career Blog

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!

,

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;

,

One way to approach this problem is to break the function foo into 2 functions

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

float foo_core(vector<int>& workingStorage) { 
  ... 
  // rest of original foo
}

,

vector<int> temp;
vector<int>& workingStorage = (aContainer!=NULL) ? aContainer->storage : temp;

,

The design is apparently horrible. But given that an optional externally provided storage is what you want, JaredPar (his answer) has a good idea. Cleaning that further up:

struct Container
{
    vector<int> storage;
};

double foo( vector<int>& workingStorage )
{
    workingStorage.reserve( 1000000 );
    //....use workingStorage to calculate something......
    return calculated_result;
}

double foo( Container& storageProvider )
{
    return foo( storageProvider.storage );
}

double foo()
{
    vector<int> storage;
    return foo( storage );
}

Cheers & hth.,

,

Why don’t you make sure that aContainer->storage is initialized before you pass aContainer it to foo. That makes your code lot more neater. Have an assert statement at the start of the function to check aContainer->storage for NULL.

Leave a Comment