-1

I've got the following scenario:

bool bWantToWait = getRandomBool();

if (bWantToWait){
    std::future<bool> bSuccesfullWait = this->doStartWait();
}

//lots of lines of code
//even more lines of code
//doExecuteSomethingWithAsyncCallback

if (bWantToWait){
    return bSuccessfullWait.get();
}
return true;

Now of course bSuccesfullWait is out of scope in the second if statement, so this won't compile. But basically what I want is that doStartWait() "initializes" a wait. I don't want to initialize this wait if I don't have to, as it's relatively resource intensive.

An example application for this would be networking. this->doStartWait(); would open up a port, and return a future that returns when a message comes in. this->doExecuteSomethingWithAsyncCallback(); would send something to a different PC, which would then return a message on the port opened in this->doStartWait();. You'd want to make sure that the port is opened before sending a message, so you don't miss the reply.

What I've resorted to is the following:

bool bWantToWait = getRandomBool();

auto fnExec = [&]()->void{
    //lots of lines of code
    //even more lines of code
    //doExecuteSomethingWithAsyncCallback
};

if (bWantToWait){
    std::future<bool> bSuccesfullWait = this->doStartWait();
    fnExec();
    return bSuccessfullWait.get();
}
fnExec();
return true;

The downside of this approach is that the code is not in chronological order any more, and that ideally I'd like to prevent the overhead of function calls. An alternative would be to make a std::future<bool>*, or std::unique_ptr<std::future<bool>>, but that also adds overhead. The least overhead method would be raw pointers, but that still uses the heap instead of just the stack.

Am I missing an obvious solution to having a variable "stay in scope" over two if statements?

  • 1
    The "overhead" you are referring to is insignificant. You are not in a tight loop, you have "lots of lines of code" to execute. – Martin Maat Aug 06 '19 at 14:15

1 Answers1

1

Aren't you just over-complicating things? If I understand you correctly your problem is that bSuccesfullWait is out of scope near the end of your code.

Just shift the variable declaration before the (conditional) initialization:

    std::future<bool> bSuccesfullWait;  // now in scope.
    if (bWantToWait){
        bSuccesfullWait = this->doStartWait();
    }
    //lots of lines of code

    if (bWantToWait){
        return bSuccessfullWait.get();
    }
    return true;
Robert Harvey
  • 198,589
  • 55
  • 464
  • 673