gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:41:52 26 4
gpt4 key购买 nike

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

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() 是我程序中最常调用的函数之一(根据我的探查器),因此我宁愿不通过将类的状态作为函数参数传递来创建开销.

所以我的问题是:我应该像瘟疫一样避免这种模式,还是在某些情况下可以接受?

最佳答案

现在你的代码已经定义好了。 The order of initialization of nonstatic data members of a class is :

Then, nonstatic data members shall be initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

并且因为 _x_collection 之前声明,_x 将被初始化,因此可以在 functionThatDependsOnTheStateOfTheClass().

关于c++ - 在构造函数初始化列表中调用非静态函数,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40674336/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com