【发布时间】:2018-01-04 06:32:08
【问题描述】:
注意:C++98 是唯一可用的标准
我正在尝试创建一个大型数组以在运行时用作查找表,但我在编译时知道所有表信息。从概念上讲,我知道我可以通过静态分配节省大量运行时间,但我在使用 C++ 语法时遇到了一些问题。
或者,简单地说,我正在寻找正确的方法来做一个类的版本
const int arr[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
通过在编译时了解我想要存储在对象数组中的所有内容,尽可能节省成本。
这是我的条目类示例
class foo{
private:
const int a;
const char * b;
public:
foo(const int a, const char * b);
int get_a(void) const{
return this->a;
}
const char * get_b(void) const{
return this->b;
}
};
foo::foo(
const int a,
const char * b
) :
a(a),
b(b){
}
可以用这个 main 运行
//Is this array statically allocated at compile time or dynamically allocated at run time with the constructors of foo?
foo arr[2]={
foo(0,"b0"),
foo(1,"b1")
};
int main(void){
for(int i=0;i<2;i++){
std::cout<<arr[i].get_a()<<std::endl;
std::cout<<arr[i].get_b()<<std::endl;
}
return 0;
}
【问题讨论】:
-
不是动态分配的,存储会提前预留。但它可能是动态初始化的。无论哪种方式,一切都会在它第一次使用之前发生。你确定要走“公共吸气剂的私人数据”路线吗?在我看来,您可以使用简单的聚合来完成。