从堆分配时堆栈溢出

时间:2010-11-26 14:22:22

标签: c++ boost stack overflow

这到底发生了什么?

#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 个答案:

答案 0 :(得分:7)

问题是Toy()个对象被传递给boost::assign::list_of()。这些是在复制到Box对象(将在堆上)之前在堆栈上创建的临时对象

为了避免在堆栈上创建它们,你可以这样做:

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

答案 1 :(得分:1)

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

在堆栈上生成(巨型)临时(woo!),传递给玩具的构造函数。

答案 2 :(得分:1)

堆栈溢出发生在Box()构造函数中。我不确定boost :: assign是如何工作的,但看起来你传递给它,作为参数,类型为Toy的三个临时变量。像它们一样构建在堆栈上。