Stack Overflow knows when to use the new keyword and when not to.
I've been using C++ for a while and have been wondering about the new word.Should I be using it or not?
They don't seem that different from an implementation perspective.The 1st method is what I'm used to, and my primary language is C#.
A large array was going out of scope and I used the new word for heap memory.Being returned from an event.When I switched to heap usage, the elements were in tact because half of them were corrupt outside of scope.I'm happy!
A friend of mine recently told me there's a simple rule for using a new word; every time you type it, you should remove it.
You have to put the deletion somewhere to prevent memory leaks.When you cut and paste it.
Given the constraints, you choose the method that works best for you.
Everything not allocated with new behaves like value types in C#, and people often say that those objects are allocated on the stack, which is probably the most common/obvious case, but not always true.Everything allocated with new is allocated on the heap, and a pointer to it is returned, exactly like reference types in C#.
If the object is a member of another class, or if the stack pointer is set correctly, the size of that other class has to be adjusted.That's why C# has reference types.Because of reference types, we can decide how much memory to ask for.The same applies here.Only arrays with constant size can be allocated with automatic storage duration.Dynamically sized arrays have to be allocated on the heap.
If no other storage type is specified, anything allocated on the stack has an "automatic" storage duration.
Automatic storage duration means exactly what it sounds like, the duration of the variable is handled automatically.Anything on the heap has to be manually deleted by you.Here's an example.
On line 2, it allocates a bar object to the heap.The duration is dynamic.
When the function returns, b2 goes out of scope and the order of destruction is opposite of construction.The memory it occupies is simply freed because b2 is just a pointer.The bar instance on the heap is not touched.The pointer had an automatic duration.Since b has an automatic duration, the destructor is called and the memory is freed.
The barinstance is on the heap.It's probably still there.We leaked memory because no one deleted it.
When it goes out of scope, anything with an automatic duration is guaranteed to have its destructor called.That's useful.Anything allocated on the heap lasts as long as we need it to, and can be dynamically sized, as in the case of the array.That is useful as well.That can be used to manage our memory allocations.What if the Foo class deleted the memory from its destructor by allocating it to the heap in its constructor?We could get the best of both worlds, safe memory allocations that are guaranteed to be freed again, but without the limitations of forcing everything onto the stack.
It's pretty much how most C++ code works.The std::vector is in the standard library.It can be allocated on the stack and dynamically sized.It allocates memory on the heap as needed.The user of the class never sees this, so there's no chance of leaking memory or forgetting to clean up what you allocated.
This principle can be applied to any resource that needs to be acquired and released.There are network sockets, files, database connections.All of them can be obtained in the destructor, so you're guaranteed that they'll be freed again.
Don't use new/delete from your high level code.Wrap it in a class that can manage the memory for you and make sure it gets freed again.There may be exceptions to this rule.Smart pointers require you to call new directly, and then pass the pointer to its constructor, which will make sure deletion is called correctly.This is still an important rule of thumb.
By the context, this is almost never determined by your typing preferences.If you need to keep the object across a few stacks or if it's too heavy for the stack, you allocate it on the free store.You are also responsible for releasing the memory since you are allocating an object.The operator that you want to look at is the deletion operator.
People have invented things to make free-store management easier to use.You should take a look at these.They might be able to help with your typing issues.
You should use smart pointers such as std::shared_ptr and std make_shared.You don't have to worry about memory leaks as much.If you're more advanced, the best practice would be to create a small class dedicated to object lifecycle issues, such as a custom smart pointer.
Behind the scenes, these smart pointers are still performing dynamic allocation and deallocation, so code using them would still have the associated overhead.These issues have been covered in other answers, and how to make design decisions on when to use smart pointers versus just creating objects on the stack or incorporating them as direct members of an object, well enough that I won't repeat them.My executive summary would be, "Don't use smart pointers or dynamic allocation until something forces you to."
It is likely that you are writing for performance.The free store is slower than the stack so only use it when you need it.
When you don't know the size of an array or the object is large, you need a new object.
Try not to use deletion.Instead of wrapping your new, use a smart pointer.The smart pointer should be deleted.
Sometimes a smart pointer isn't smart.It's never a good idea to store std in a container.The pointer will be deleted too soon because of copy operations inside the container.Another case is when you have a large container of pointers.As it bumps the reference counts up and down, boost will have a ton of speed overhead.The best way to go about it is to put the container into another object and give it a destructor that will destroy everything in it.
You're storing that on call stack without the new word.Stack overflow can be caused by storing excessively large variables.
The answer is yes, the second form creates an object on the heap with the unfortunate side effect that you have to manage its lifetime by explicitly calling deletion.
If your variable is only used in the context of a single function, you're better off using a stack variable.You don't have to manage the lifetime of stack variables because they are constructed and destructed automatically.It is slow to allocate a variable on the heap.If you use stack variables instead of heap variables, you will see a performance improvement.
If the stack variable has a large memory footprint, you run the risk of overflowing it.On Windows, the stack size of each thread is 1 MB.It is not likely that you will create a stack variable that is 1 MB in size.The stack variables in all of the functions take up space on the same stack.Depending on how deep the function is, it can run into this problem quickly.If this is a problem, you can either increase the size of the stack or allocate the variable on the heap using the new operator.
It is more likely that your variable needs to live beyond the scope of your function.You would allocate the variable on the heap so that it can be reached outside the scope of the function.
Do you expect myClass to exist outside of a function or are you passing it out?When you aren't allocating on the heap, it's all about scope.It goes away when you leave the function.The attempt to create a local object of some class in a function and return it without allocating it on the heap is one of the classic mistakes made by beginners.I used to do this kind of thing in the past.
The second method creates an instance on the stack, along with a list of parameters that are passed into the function.
The first method makes room for a pointer on the stack, which you've set to the location in memory where a new MyClass has been allocated.
The first method requires that you destroy what you create with new, whereas in the second method the class is freed when it falls out of scope.