在C ++函数中使用多个范围块 [英] On using several scoped blocks in a C++ function

查看:159
本文介绍了在C ++函数中使用多个范围块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始越来越多地使用连续的范围块来编写长C ++算法函数,如下:

I am starting to be more and more attracted to writing long C++ algorithmic functions using successive scoped blocks, as follows:

void my_algorithm(const MyStruct1 &iparam1, MyStruct2 &oparam2)
{
    // First block
    MyStruct3 intermediate_var3;
    {
        double temporary_var;
        // Functional step 1.1
        // Functional step 1.2
        intermediate_var3 = ...
    }
    // Second block
    MyStruct4 intermediate_var4;
    {
        double temporary_var;
        // Functional step 2.1
        // Functional step 2.2
        intermediate_var4 = ...
    }
    // Final block
    {
        int temporary_var;
        oparam2 = ...
    }
}



开始认为它是澄清函数结构和限制临时变量的范围的好方法(例如计数器 i j k 等)。我看到这样的范围块在C函数中启用新的声明是有意义的(参见

I am starting to think it is a good way to clarify the function structure and to limit the scope of temporary variables (such as counters i, j, k etc). I saw that such scope blocks make sense in C functions to enable new declarations (see Why enclose blocks of C code in curly braces?).

在C ++的上下文中,这是好的还是坏的做法?

In the context of C++, is this good or bad practice ?

推荐答案

这是一个明确的标志,你应该将这个单独的块提取到单独的函数中。

This is a clear sign, that you should extract this separate blocks into separate functions.

MyStruct3 DoSth3(params)
{
    double temporary_var;
    // Functional step 1.1
    // Functional step 1.2
    return ...
}

MyStruct4 DoSth4(params)
{
    double temporary_var;
    // Functional step 2.1
    // Functional step 2.2
    intermediate_var4 = ...
}

void my_algorithm(const MyStruct1 &iparam1, MyStruct2 &oparam2)
{
    // First block
    MyStruct3 intermediate_var3 = DoSth3(params);

    // Second block
    MyStruct4 intermediate_var4 = DoSth4(params);

    int temporary_var;
    oparam2 = ...
}

将担心 DoSth3 DoSth4 是公开的,因为它们应该是private 在my_algorithm 。在这种情况下,您可以通过以下方式解决:

It may happen, that you'll be worried about DoSth3 and DoSth4 being public, as they should be private in the context of my_algorithm. In such case you can solve it in the following way:

class my_algorithm
{
private:
    static MyStruct3 DoSth3(params);
    static MyStruct4 DoSth4(params);

public:
    static void Perform(const MyStruct1 &iparam1, MyStruct2 &oparam2);
};

这篇关于在C ++函数中使用多个范围块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆