Liu Hao
Liu Hao

Reputation: 512

C++ create class object in stack or heap when push it to container?

I have read the this SO issue,When is it best to use the stack instead of the heap and vice versa?, It seems the stack has a limited size, so you can not alloc large object in the stack.

I have some code , which push an object to a container, see this link on online ide, http://cpp.sh/9xxea

So, should I prefer one to another ?

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;

Upvotes: 0

Views: 1049

Answers (1)

eerorika
eerorika

Reputation: 238341

So, should I prefer one to another ?

I suggest not creating the object separately at all. Neither stack, nor heap. Create the object into the vector directly:

 persons.emplace_back(10, "kit");

That said, CPerson is quite small and you can fit hundreds of thousands (or less, depends vastly on the size of your stack) of them on the stack, so I wouldn't worry whether that one does.

Upvotes: 1

Related Questions