Reputation: 531
What exactly is happening here?
#include <boost/array.hpp>
#include <boost/assign/list_of.hpp>
struct Toy {
int m_data[100000];
};
struct Box {
Box()
: m_toys( boost::assign::list_of( Toy() )( Toy() )( Toy() ) )
{}
boost::array<Toy,3> m_toys;
};
void main()
{
Box* box = new Box; // This causes stack overflow
}
Upvotes: 3
Views: 197
Reputation: 100658
The problem is the Toy()
objects being passed to boost::assign::list_of()
. These are temporary objects which are created on the stack before being copied to the Box
object (which will be on the heap)
to avoid creating them on the stack, you could do this:
Box() : m_toys()
{
Toy* t = new Toy;
for (int i = 0; i < 3; ++i)
m_toys.push_back(*t);
delete t;
}
Upvotes: 7
Reputation: 61361
The stack overflow is happening in the Box() constructor. I'm not sure how does boost::assign work, but it looks like you're passing to it, as arguments, three temporary variables of type Toy. Constructed, as they are, on the stack.
Upvotes: 1
Reputation: 42872
The value
boost::assign::list_of( Toy() )( Toy() )( Toy() )
generates a (giant) temporary on the stack (woo!) that is passed to the constructor for toys.
Upvotes: 1