Reputation: 13853
If I use std::vector<> or std::string, do I need to allocate them in heap as well. For example:
int main() {
std::vector<int>* p = new std::vector<int>();
delete p;
}
In Java and C#, objects are always allocated in heap using this syntax. I wonder is it efficient to do the same thing in C++? Because whenever I create a class in C++, I usally mix between stack and heap variables. Let's say:
class simple {
int a;
double b;
std::string c;
std::vector<int> d;
....
};
I wonder what's the best practice should I follow when using object in C++?
Thanks,
Chan
Upvotes: 1
Views: 765
Reputation: 10979
You should avoid creating objects with large size on stack, because casual stack overflow on stress (large input data) is rarely revealed by testing and so will make your end users unhappy that your software crashes.
About string and vector and other STL containers you should not worry, because they use dynamic allocation internally. So the answer is NO, it is safe to construct them into stack and it is usually overkill to allocate them dynamically.
What might be dangerous are static-sized arrays, things that enwrap such arrays like boost::array or classes that have such as data members. Experts often use pimpl idiom to make their classes internally dynamic.
Stack is extremely quick, but use its quickness only where it really benefits the performance. It is safer to be careful with it. Avoid taking dangerous idioms like "I allocate everything on stack".
Upvotes: 2
Reputation: 4136
No; in general, use the stack unless the variable's lifetime exceeds that of the function.
The container classes will allocate their own memory from the heap; the only data on the stack is whatever bookkeeping the container class needs such as a pointer to the head, size, etc.
Additionally I would recommend avoiding manual new/delete and utilizing shared_ptr etc techniques.
Upvotes: 1
Reputation: 73443
I try to allocate the objects on stack whenever possible as I don't have to worry about releasing the memory in such case. Only when I explictly want to control the life time of an object I will allocate the object on the heap. Even if the object internally allocates memory on heap, you can still create the object itself on the stack. There is no restriction on that.
Upvotes: 3