Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I terminate the scope of a C++ variable without ending a block?

I would like to do something like the following pattern:

T* const pT = findT();
// Do some work
T* const pT2 = new T( *pT );
// Mutate the object pT2 refers to
delete pT;
// At this point, I want the scope of pT to end.
// I do not want the scope of pT2 to end

I know I can end scope by ending a block, but it ends up like this:

T* pT2 = 0;
{
    T* const pT = findT();
    // Do some work
    pT2 = new T( *pT );
    // Mutate the object pT2 refers to
    delete pT;
}

This causes pT2 to lose its const qualifier because I have to assign to it after it's declared.

I want my cake and I'd like to eat it too, I want clear constness and proper scoping!

Is there any way to end scope on a variable other than by ending a block? If not, are there any plans to extend the standard to support this?

like image 214
Don Neufeld Avatar asked Sep 17 '25 03:09

Don Neufeld


1 Answers

You can use lambdas:

T* const pT = []() -> T* {
    T* pT;
    // Do whatever the hell you want with pT
    return pT;
}();
like image 198
Benjamin Lindley Avatar answered Sep 19 '25 17:09

Benjamin Lindley