C ++在将其推送到容器时在堆栈或堆中创建类对象?

时间:2017-06-16 12:49:32

标签: c++

我已阅读此SO问题When is it best to use the stack instead of the heap and vice versa?, 看起来堆栈的大小有限,所以你不能在堆栈中分配大对象。

我有一些代码,它将对象推送到容器,请参阅在线ide上的此链接http://cpp.sh/9xxea

那么,我应该更喜欢彼此吗?

void AddPerson(const CPerson& p)
{
    std::cout << "push back" << std::endl;
    persons.push_back(p);
    std::cout << "size " << persons.size() << std::endl;
}
void AddPerson()
{
    CPerson cp(10, "kit");
    std::cout << "push back" << std::endl;
    //I know push_back will copy the element and push the copied object(which is created on heap ?), when function returns, cp will be "freed".
    //so this function is better than function AddPerson(const CPerson&) ?
    persons.push_back(cp);
    std::cout << "size " << persons.size() << std::endl;
}
std::vector<CPerson> persons;

1 个答案:

答案 0 :(得分:1)

  

那么,我应该更喜欢彼此吗?

我建议不要单独创建对象。既不堆叠也不堆积。直接在向量中创建对象:

 persons.emplace_back(10, "kit");

那就是说,CPerson非常小,你可以在堆栈上安装数十万(或更少,在很大程度上取决于堆栈的大小),所以我不担心是否会

相关问题