在C++中创建多个静态对象

Create multiple static objects in C++

本文关键字:静态 对象 创建 C++      更新时间:2023-10-16

长话短说,我需要在一个函数中创建许多对象。是否可以在不复制和粘贴的情况下执行此操作?

基本上,我想要的效果是这个

class foo() { .... }
void bar()
{
    static foo obj1;
    static foo obj2;
    static foo obj3;
    ...
    ...
    static foo obj501;
}

非常感谢您的帮助:)

更新:似乎我的动机背后的问题是必需的:)

我试图创建一个测试用例来测试我们对atexit()实现的限制,该限制将在ARM艺术体系结构上运行。限制是目前有固定数量的静态对象可以注册到__aeabi_atexit(为了论证起见,假设这个数字是500)。如果注册了更多的对象,函数就会简单地返回(没有任何错误消息),导致静默失败,这不是很好。现在,我已经修复了atexit()实现中的"无意义返回"部分,但需要测试修复,为此,我需要创建至少500个静态对象。

对于这样的一次性测试来说,复制和粘贴并不是一个糟糕的解决方案。要优化它,您应该在复制之前重新选择整个块,这样每次都可以将块的大小增加一倍——只需8次粘贴就可以达到512个对象。

下一个问题是给每个对象一个唯一的名称。为此,我们转向低级宏:

#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); 
}