0

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;
Liu Hao
  • 472
  • 4
  • 24
  • Put the code in the question not in a link. TIA. – Borgleader Jun 16 '17 at 12:51
  • If you are pushing to the container, it will end-up on heap anyway. – Kimi Jun 16 '17 at 12:52
  • @Borgleader edited – Liu Hao Jun 16 '17 at 12:53
  • 1
    These two functions are essentially the same (assuming the parameter passed to the first version was on the stack before being passed in), although in the second example `persons.emplace_back(10, "kit");` would be much better. No need for a temporary object then. – Borgleader Jun 16 '17 at 12:53
  • @Borgleader So, if the parameter to the first version was allocated on heap, then after call the function, I need manual delete it ? – Liu Hao Jun 16 '17 at 12:57
  • Yes, if you new something, you must delete it. – Borgleader Jun 16 '17 at 12:59
  • If you are not at the point where its easy to explain the difference between the two functions, I suggest you forget about stacks and heaps, it's not that critical – Passer By Jun 16 '17 at 13:17
  • You should dynamically allocate objects when you need to control their lifetime, create automatic variables otherwise. Think about stack limit when there is issue with your program. – Slava Jun 16 '17 at 14:46

1 Answers1

1

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326