在堆上而不是堆栈上初始化 C++ 结构

Initialize C++ struct on the heap instead of the stack

由于我不想在这里深入的原因,我必须将在其他地方编写的一些代码集成到我们的程序中,同时对他们的代码进行最少的更改。该代码有一个构造函数,它创建一个结构作为局部变量(在堆栈上),然后将它分配给一个成员变量,如下所示:

struct S
{
   // lots of real_T's and uint32_T's and structs and structs within structs
};

class C
{
private:
   S s;
   // among other members
};

C::C()
{
   S tempS = {
      // more than 52k lines of code!!!
   };
   s = tempS;
}

他们的代码是从某种 Matlab 模型自动生成的,是的,在结构的初始化程序中有超过 52,000 行代码。 由于显而易见的原因导致堆栈溢出,这是我试图解决的实际问题。

Class C 正在堆上创建(实际上它是围绕从 C 派生的 class 的包装器),我的理解是这意味着 C.s 也在堆上堆.

请注意,我们目前使用的是 Visual Studio 2010,但我们很快就会转向 Visual Studio 2015(TM),因此适用于任何一个的解决方案都很好。

问题

  1. 有没有办法直接初始化C.s?

  2. 或者有没有办法在将 tempS 复制到 C.s 之前在堆上创建 tempS 而无需重写 52k 行初始化代码?

None 这些方式似乎对我有用:http://en.cppreference.com/w/cpp/language/value_initialization

(6) 看起来像我想要的:

S * tempS = new S {
    // more than 52k lines of code!!!
};

但是会导致编译错误:"error C2143: syntax error : missing ';' before '{'"

Is there a way to initialize C.s directly?

是的,只需替换此代码:

C::C()
{
   S tempS = {
      // more than 52k lines of code!!!
   };
   s = tempS;
}

有了这个:

C::C() :
   s {
      // more than 52k lines of code!!!
   }
{
}

尽你所能see here它应该在支持 C++11 或更高版本的编译器上工作

我会考虑使 tempS 成为 C 的私有静态常量成员(并在另一个编译单元中定义它)。 initializer/prototype 基本上是数据,只会使代码不可读。此外,无论 where/how 你如何定义它,这些数据都在你的二进制文件中的某个地方,所以你最好把它明确化。

我的建议是在 class S 中创建一个构造函数,将所有成员的值作为参数。按照结构中定义的相同顺序定义构造函数的参数列表。

struct S
{
   // lots of real_T's and uint32_T's and structs and structs within structs
   S(/*parameter_lsit*/) : /*initializer_list*/ {}
};

并像 -

一样初始化它
S * tempS = new S (
    // more than 52k lines of code!!!
);