在C++中创建多个静态对象
Create multiple static objects in C++
长话短说,我需要在一个函数中创建许多对象。是否可以在不复制和粘贴的情况下执行此操作?
基本上,我想要的效果是这个
class foo() { .... }
void bar()
{
static foo obj1;
static foo obj2;
static foo obj3;
...
...
static foo obj501;
}
非常感谢您的帮助:)
更新:似乎我的动机背后的问题是必需的:)
我试图创建一个测试用例来测试我们对atexit()实现的限制,该限制将在ARM艺术体系结构上运行。限制是目前有固定数量的静态对象可以注册到__aeabi_atexit(为了论证起见,假设这个数字是500)。如果注册了更多的对象,函数就会简单地返回(没有任何错误消息),导致静默失败,这不是很好。现在,我已经修复了atexit()实现中的"无意义返回"部分,但需要测试修复,为此,我需要创建至少500个静态对象。
下一个问题是给每个对象一个唯一的名称。为此,我们转向低级宏:
#define STATIC_OBJECT static foo obj##__LINE__
STATIC_OBJECT;
STATIC_OBJECT;
...
如果你。。。
template <int N> struct HasStaticMember : public HasStaticMember<N - 1> {
static foo mFoo;
};
template <> struct HasStaticMember<1> {
static foo mFoo;
};
void bar() { HasStaticMember<501> foo; }
编辑:VS2010不喜欢501模板递归。您可能仍然需要为每个结构放入5个变量,然后使用101个模板参数。。。有关其他建议,请参阅下面的评论。
我会使用递归模板函数:
template <int N> void makeStatic() {
static foo s_foo;
makeStatic<N-1>();
};
template <> void makeStatic<0>() {
static foo s_foo; // comment this out to get 512, otherwise you get 513 objects. :)
};
void bar() { makeStatic<512>(); }
。。从上面的评论中添加作为答案,以防对其他人有用,我想。。。
#include <boost/preprocessor/repetition/repeat.hpp>
#define DECL(z, n, text) text ## n;
struct bar{};
void foo()
{
BOOST_PP_REPEAT(5, DECL, static bar temp)
}
int main(void)
{
foo();
}
我不明白你为什么要这么做。难道你不能只使用数组或向量吗?
如果您真的想这样做,可以尝试使用标记粘贴运算符(##)
您能使用数组或向量吗?
class foo() { .... }
void bar()
{
// Using an array:
static foo obj_arr[502];
// or
// Using a vector
// Size given in the constructor to tell it how many objects you're going to need
// This may or may not be needed depending on how how your code is set up, since
// vectors automatically resize when elements are added to them.
static std::vector<foo> obj_vec(502);
}
相关文章:
- CPU 瓶颈;处理具有许多非静态对象的 3D 场景渲染的简单方法
- 我可以读取静态对象中的文件.txt吗?C++
- 通过 Gazebo 世界插件将静态对象附加到机器人链接
- 将对象创建为全局/静态对象会崩溃,而本地对象不会崩溃
- 内联函数的函数本地静态对象是否在共享对象文件之间共享?
- 将 C# 对象(包含静态对象成员)作为参数传递给 C++/CLI 程序
- 完全释放静态对象内存
- 静态对象指针
- C++文件中.cpp静态对象声明
- C++类中定义静态对象
- 在初始化类的静态对象之前,是否保证初始化该类的静态成员?
- 静态对象如何调用私有构造函数
- cpp 静态对象实例化
- 等效于 Java 静态对象类C++
- 我怎么知道C++编译器是否制作线程安全的静态对象代码
- 在dlclose()之前破坏的静态对象
- 有没有办法为静态对象成员定义一个符合开关标准的常量?
- c++ 防止类共享静态对象
- 什么时候构造函数为静态对象
- 为什么本地静态对象的初始化使用隐藏的防护标志?