Bar*_*lly 9 c++ g++ clang c++11
在过去,我使用gcc的C99风格的 C++ 复合文字扩展来编码代码中的嵌套常量数据结构.这是一个例子:
#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 << "\n";
}
Run Code Online (Sandbox Code Playgroud)
我们的想法是为这些相当大的常量结构使用静态存储持续时间,初始化成本为零,实际上除非需要,否则不需要将任何内容分页到内存中.
然而,这不再适用于最新版本的clang,最新的OS X正在以"gcc"的名义捆绑clang.所以我需要一个不同的解决方案
在C++中,最符合标准的标准是什么?
我并不特别想支付构建这些结构中所有对象的成本,所以如果可以避免,那就太好了.
C++ 11 统一初始化语法应该工作:
const Tree* const tree = new Tree{"top",
new Tree{"left", nullptr, nullptr},
new Tree{"right", nullptr, nullptr}
};
Run Code Online (Sandbox Code Playgroud)
否则,只需创建一个构造函数,将名称和子树作为参数.
如果您不希望动态分配结构,则必须自己创建每个结构,然后使用例如address-of运算符将它们链接在一起:
namespace
{
const Tree leftTree{"left", nullptr, nullptr};
const Tree rightTree{"right", nullptr, nullptr};
const Tree topTree{"top", &leftTree, &rightTree};
}
const Tree* const tree = &topTree;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1509 次 |
最近记录: |