Reputation: 23
For reasons that I do not want to get into here, I have to integrate some code written elsewhere into our program with minimal changes to their code. The code has a constructor that creates a struct as a local variable (on the stack), then assigns it to a member variable like this:
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;
}
Their code is autogenerated from some sort of Matlab model and, yes, that is over 52,000 lines of code in the initializer for the struct. It causes a stack overflow for obvious reasons, which is the actual problem that I am trying to solve.
Class C is being created on the heap (actually it's the wrapper around the class derived from C), and my understanding is that means that C.s is also on the heap.
Note that we are currently using Visual Studio 2010, but we will be moving to Visual Studio 2015 soon(TM), so solutions that work in either are fine.
Questions
Is there a way to initialize C.s directly?
Or is there a way to create tempS on the heap before copying it to C.s without rewriting the 52k lines of initializer code?
None of these ways seem to be working for me: http://en.cppreference.com/w/cpp/language/value_initialization.
(6) looks like what I want:
S * tempS = new S {
// more than 52k lines of code!!!
};
But it causes a compile error: "error C2143: syntax error : missing ';' before '{'"
Upvotes: 2
Views: 3751
Reputation: 561
My suggestion is to create a constructor in class S
that take all the members' values as parameter. Define the parameter list of the constructor in same order they are defined in the structure.
struct S
{
// lots of real_T's and uint32_T's and structs and structs within structs
S(/*parameter_lsit*/) : /*initializer_list*/ {}
};
And initialize it like -
S * tempS = new S (
// more than 52k lines of code!!!
);
Upvotes: 0
Reputation: 160
I would consider making tempS
a private static constant member of C
(and defining it in another compilation unit). This initializer/prototype is basically data and just makes the code unreadable. Also, this data somewhere in your binary no matter where/how you define it, so you might as well make that explicit.
Upvotes: 0
Reputation: 44258
Is there a way to initialize C.s directly?
yes, just replace this code:
C::C()
{
S tempS = {
// more than 52k lines of code!!!
};
s = tempS;
}
with this:
C::C() :
s {
// more than 52k lines of code!!!
}
{
}
as you can see here it should work on compiler, that supports C++11 or later
Upvotes: 4