0
我讀過這個SO問題,When is it best to use the stack instead of the heap and vice versa?, 看來棧的大小有限,所以你不能在堆棧中分配大對象。C++在將堆棧或堆棧中的類對象推入容器時創建類對象?
我有一些代碼,這推動了對象的容器,看到網上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;
將問題中的代碼放在鏈接中。 TIA。 – Borgleader
如果您正在推送容器,它仍然會在堆上結束。 – Kimi
@Borgleader編輯 –