C ++范围定义变量?

C++ scope to define a variable?

假设我有一个名为 Tensor 的 Class,为了完全构建 class 的实例,我需要进行大量计算并定义辅助变量。在这种情况下,我看到其他人的代码使用了这样的范围:

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

我想我明白了:您在作用域中定义辅助变量是因为您将不再需要它们。我对 C++ 很陌生,这是第一次遇到这种情况。通常我在定义 Class 或函数时会看到作用域。我用谷歌搜索并在“声明点”标题下找到了一个示例 here

这是好的做法吗?我应该什么时候使用它?我应该避免它吗?跟垃圾有关系吗collection?

Is this good practice?

这不是坏习惯。

When should I use it?

一个常见的用例是 RAII 辅助类型。考虑 scoped_lock 的 cppreference 上的示例(我添加的评论):

void assign_lunch_partner(Employee &e1, Employee &e2)
{
    static std::mutex io_mutex;
    {
        std::lock_guard<std::mutex> lk(io_mutex);
        std::cout << e1.id << " and " << e2.id << " are waiting for locks" << std::endl;
    }   // <--
 
    {
    // [...]

lk 在超出范围时自动释放互斥量。这两行可能不值得将它们放在专用函数中,因此作者只是打开了一个范围,使得锁只持有互斥锁直到 } // <--.

Should I avoid it?

当代码的大小超过几行时,不引入功能而只引入作用域的整个想法不再是可维护的。虽然这纯粹是基于意见和风格问题。

Does it have anything to do with garbage collection?

没有。它与垃圾收集无关。如上所示,它与 RAII.

有关

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

减少变量的范围通常是好的,但通常最好初始化变量而不是稍后设置它们(所以你可以有 const 例如)。

创建函数或调用 lamdba 甚至比作用域更好:

/* 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.

所以除非你需要公开 a, b and/or c, 或者范围已经很短了不必担心(特别是如果有 const),我会通过上述技术缩小范围。

Does it have anything to do with garbage collection?

什么都没有。