Stack overflow on heap allocation

What exactly is going on 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
}
+3
source share
3 answers

The problem is that the objects Toy()are being passed in boost::assign::list_of(). These are temporary objects that are created on the stack before being copied to the object Box(which will be on the heap)

to avoid creating them on the stack, you can do this:

Box() : m_toys()
{
   Toy* t = new Toy;
   for (int i = 0; i < 3; ++i)
       m_toys.push_back(*t);
   delete t;
}
+7
source

Value

boost::assign::list_of( Toy() )( Toy() )( Toy() )

generates a (huge) temporary stack (woo!), which is passed to the constructor for toys.

+1
source

Box(). , boost:: , , , , Toy. , , .

+1

Source: https://habr.com/ru/post/1777073/


All Articles