Search code examples
c++scopeglobal-variables

C++ scope to define a variable?


Say I have a Class called Tensor and in order to fully construct an instance of the class I need to do a bunch of calculations and define auxiliary variables. In that context, I have seen code from somebody else that used a scope as such:

    Tensor t;
    {
        // lots of calculations to define a, b, c, ..
        t = Tensor(a, b, c, ..)
    }

I think I get the idea: you define the auxiliary variables in a scope because you won't need them again. I'm quite new to C++ and this is the first time encountering this. Typically I see the scope when defining a Class or a function. I've googled and found an example here, under the heading "Point of declaration".

Is this good practice? When should I use it? Should I avoid it? Does it have anything to do with garbage collection?


Solution

  • Is this good practice? When should I use it? Should I avoid it?

    Reduce scope of variable is generally good, but it is generally better to initialize variable instead of set them later (so you can have const for example).

    Creating a function or invoking a lamdba would be even better than the scope:

    /* const */ Tensor t1 = make_tensor(/*..*/);
    /* const */ Tensor t2 = []()
        {
            // lots of calculations to define a, b, c, ..
            return Tensor(a, b, c, ..);
        }(); // extra parents to call directly the lambda
    // a, b, c are no longer accessible, and so cannot be misused.
    

    So unless you need to expose a, b and/or c, or the scope is already short to not really have to worry about it (especially if there are const), I would reduce scope by above techniques.

    Does it have anything to do with garbage collection?

    Nothing at all.