如何在 C++ 中编码大型复杂的常量数据结构
过去,我使用 gcc 的 C99 风格的复合文字扩展C++ 在代码中编码嵌套的常量数据结构.这是一个例子:
In the past, I've used gcc's C99-style compound-literal extension to C++ to encode nested constant data structures in code. Here's an example:
#include <iostream>
using namespace std;
struct Tree {
const char *name;
const Tree *left;
const Tree *right;
};
const Tree *const tree = (Tree []) {
"top", // name
(Tree[]) {
"left",
0,
0
},
(Tree[]) {
"right",
0,
0
}
};
static void dump(const Tree *tree) {
if (!tree) {
cout << "null";
return;
}
cout << tree->name << "(";
dump(tree->left);
cout << ", ";
dump(tree->right);
cout << ")";
}
int main(void) {
dump(tree);
cout << "
";
}
我们的想法是为这些相当大的常量结构使用静态存储持续时间,初始化成本为零,并且确实不需要将任何内容分页到内存中,除非需要.
The idea is to use static storage duration for these reasonably large constant structures, with zero initialization cost, and indeed no need to page anything into memory unless needed.
但是,这在最新版本的 clang 中不再有效,并且最新的 OS X 以gcc"的名义捆绑了 clang.所以我需要一个不同的解决方案.
This no longer works in recent version of clang, however, and the latest OS X is bundling clang under the name 'gcc'. So I need a different solution.
在 C++ 中最好的符合标准的习惯用法是什么?
What's the best standard-conforming idiom for this in C++?
我并不是特别想支付在这些结构中构建所有对象的成本,所以如果可以避免这种情况,那就太好了.
I don't particularly want to pay the cost of constructing all the objects in these structures, so if that can be avoided, it would be great.
推荐答案
C++11 统一初始化 语法应该可以工作:
C++11 uniform initialization syntax should work:
const Tree* const tree = new Tree{"top",
new Tree{"left", nullptr, nullptr},
new Tree{"right", nullptr, nullptr}
};
否则,只需创建一个将名称和子树作为参数的构造函数.
Otherwise, just make a constructor taking the name and subtrees as arguments.
如果您不希望动态分配结构,则必须自己创建每个结构,然后使用例如将它们链接在一起.地址操作符:
If you don't want the structures to be dynamically allocated, you have to create each structure by itself, and then link them together using e.g. the address-of operator:
namespace
{
const Tree leftTree{"left", nullptr, nullptr};
const Tree rightTree{"right", nullptr, nullptr};
const Tree topTree{"top", &leftTree, &rightTree};
}
const Tree* const tree = &topTree;
相关文章