在构造函数初始化列表C ++中调用非静态函数

时间:2016-11-18 10:11:06

标签: c++ optimization constructor

我目前正在优化我的代码,并且在初始化我的类时我很想使用以下模式:

class MyClass
{
    MyClass(int x) :
        _x(x),
        _collection(createCollection())
    {
    }

    int functionThatDependsOnTheStateOfTheClass() const
    {
        return _x;
    }
private:
    std::vector<int> createCollection() const
    {
        std::vector<int> collection;

        // The collection is dependent on _x somehow.
        collection.push_back(functionThatDependsOnTheStateOfTheClass());

        return collection:
    }

    const int _x;
    const std::vector<int> _collection;
};

我完全明白,使代码隐式依赖于这样的初始化顺序是危险的,但代码是否以其他方式出错?

请注意,上面的代码非常简单。我想这样做的原因是:

  1. 我想将_collection标记为const。
  2. functionThatDependsOnTheStateOfTheClass()是我程序中调用最多的函数之一(根据我的分析器),所以我宁愿不通过将类的状态作为函数参数传递来创建开销
  3. 所以我的问题是:我应该像瘟疫一样避免这种模式,还是在某些情况下可以接受?

1 个答案:

答案 0 :(得分:4)

现在你的代码定义得很好。 The order of initialization of nonstatic data members of a class is

  

然后,非静态数据成员应按其顺序初始化   在类定义中声明(再次无论顺序如何)   记忆初始化者。)

由于在def show(request, pk): try: project = Project.objects.filter( pk=pk, source_language=source_language, target_languages__in=[target_language] ).first() except Exception as e: raise Http404() if not project: #instead of this do what? print message no project, return to previous page raise Http404() #return HttpResponseRedirect(request.META.get('HTTP_REFERER')) still generates error from non URL match 之前宣布_x_collection将被初始化,因此可以在_x中使用。