Can I terminate the scope of a C ++ variable without completing 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 that I can finish the area by completing the block, but it ends as follows:

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 need to assign it after it is declared.

I need my cake, and I also want to eat it, I want a clear confidence and the right scope!

Is there a way to end the scope of a variable other than block completion? If not, do you plan to expand the standard to support this?

+3
source share
4 answers

Is there a way to end the scope of a variable other than block completion?

. , , .

, ?

: , , .

+2

lambdas:

T* const pT = []() -> T* {
    T* pT;
    // Do whatever the hell you want with pT
    return pT;
}();
+2

, "block", ++ "scope". ++.

- std::auto_ptr, . , .

0

. , (, , ):

T* p1 = 0;

if (T* const p2 = findT()) {
  p1 = new T( *p2 );
  delete p2;
}
0

Source: https://habr.com/ru/post/1794596/


All Articles