What are the internal differences of choosing to use an std::vector vs a dynamically allocated array? I mean, not only performance differences like in this matching title question.
I mean, I try to design a library. So I want to offer a wrapper over an StackArray, that is just a C-Style array with some member methods that contains as a member T array[N]. No indirections and the new operator removed to force the implementor to have a array type always stored in the stack.
Now, I want to offer the dynamic variant. So, with a little effort, I just can declare something like:
template <typename T>
class DynArray
{
T* array,
size_t size,
size_t capacity
};
But... this seems pretty similar to a base approach to a C++ vector.
Also, an array stored in the heap can be resized by copying the elements to a new mem location (is this true?). That's pretty much the same that makes a vector when a push_back() operation exceeds its allocated capacity, for example, right?
Should I offer both API's if exists some notable differences? Or I am overcomplicated the design of the library and may I just have my StackArray and the Vector should be just the safe abstraction over a dynamically allocated array?
First there is a mindset (usually controversial) between the usage of the modern tools that the standard provides and the legacy ones.
You usually must be studing and asking things about C++ modern features, not comparing them with the old ones. But, for learning purposes, I have to admit that it's quite interesting dive deep somethimes in this topics.
With that in mind, std::vector is a collection that makes much more that just care about the bytes stored in it. There is a constraint really important, that the data must lie in contiguous memory, and std::vector ensures this in its internal implementation. Also, has an already well known, well tested implementation of the RAII pattern, with the correct usage of new[] and delete[] operators. You can reserve storage and emplace_abck() elements in a convenient and performant way which makes this collection really unique... there are really a lot of reasons that shows why std::vector is really different from a dynamically allocated array.
Not only is to worry about manual memory management, which almost an undesirable thing to do in modern C++ (embedded systems, or operating system themselves are a good point to discuse this last sentence). It's about to have a tool, std::vector<T> that makes your life as developer easier, specially in a prone-error language like C++.
Note: I say error-prone because it's a really hard to master language, which needs a lot of study and training. You can make almost everything in the world, and has an incredible amount of features that aren't begginer friendly. Also, the retrocompatibility constraint makes it really bigger, with literally thousand of things that you must care about. So, with a great power, always comes a great responsability.
I am currently using Boehm Garbage Collector for a large application in C++. While it works, it seems to me that the GC is overkill for my purpose (I do not like having this as a dependency and I have to continually make allowances and think about the GC in everything I do so as to not step on its toes). I would like to find a better solution that is more suited to my needs, rather than a blanket solution that happens to cover it.
In my situation I have one specific class (and everything that inherits from that class) that I want to "collect". I do not need general garbage collection, in all situations except for this particular class I can easily manage my own memory.
Before I started using the GC, I used reference counting, but reference cycles and the frequent updates made this a less than ideal solution.
Is there a better way for me to keep track of this class? One that does not involve additional library dependancies like boost.
Edit:
It is probably best if I give a rundown on the potential lifespan of my object(s).
A function creates a new instance of my class and may (or may not) use it. Regardless, it passes this new instance back to the caller as a return value. The caller may (or may not) use it as well, and again it passes it back up the stack, eventually getting to the top level function which just lets the pointer fade into oblivion.
I cannot just delete the pointer in the top level, because part of the "possible use", involves passing the pointer to other functions which may (or may not) store the pointer for use somewhere else, at some future time.
I hope this better illustrates the problem that I am trying to solve. I currently solve it with Boehm Garbage Collector, but would like simpler, non dependency involving, solution if possible.
In the Embedded Systems world, or programs that are real-time event critical, garbage collection is frowned upon. The point of using dynamic memory is bad.
With dynamic memory allocation, fragmentation occurs. A Garbage Collector is used to periodically arrange memory to reduce the fragmentation, such as combining sequential freed blocks. The primary issue is when to perform this defragmentation or running of the GC.
Some suggested alternatives:
Redesign your system to avoid dynamic memory allocation.
Allocate static buffers and use them. For example in an RTOS system, preallocate space for messages, rather than dynamically allocating them.
Use the Stack, not the Heap.
Use the stack for dynamically allocated variables, if possible. This is not a good idea if variables need a lifetime beyond the function execution.
Place limits on variable sized data.
Along with static buffers, place limits on variable length data or incoming data of unknown size. This may mean that the incoming data must be paused or multiple buffering when the input cannot be stopped.
Create your own memory allocator.
Create many memory pools that allocate different sized blocks. This will reduce fragmentation. For example, for small blocks, maybe a bitset could be used to determine which bytes are in use and which are available. Maybe another pool for 64 byte blocks is necessary. All depends on your system's needs.
If you really just need special handling for the memory allocations associated with a single class, then you should look at overloading the new operator for that class.
class MyClass
{
public:
void *operator new(size_t);
void operator delete(void *);
}
You can implement these operators to do whatever you need to track the memory: allocate it from a special pool, place references on a linked list for tracking, etc.
void* MyClass::operator new(size_t size)
{
void *p = my_allocator(size); // e.g., instead of malloc()
// place p on a linked list, etc.
return p;
}
void MyClass::operator delete(void *p)
{
// remove p from list...
my_free(p);
}
You can then write external code that can walk through the list you are keeping to inspect every currently-allocated instance of MyClass, GC'ing instances as appropriate for your situation.
With memory, you should always try and have clear ownership and knowledge of lifetime. Lifetime determines where you take the memory from (as do other factors), ie stack for scope lived, pool for reused, etc. Ownership will tell you when and if to free memory. In your case, the GC has the ownership and makes the decision when to free. With ref counting, the wrapper class does this logic. Unclear ownership leads to hard to maintain code if manual memory management is used. You must avoid use after free, double frees, and memory leaking.
To solve your problem, figure out who should keep ownership. This will dictate the algoritm to use. GC and ref counting are popular choices, but there are infinetly many. If ownership is unclear, give it to a 3rd party whose job it is to keep track of it. If ownership is shared, make sure all parties are aware of it perhaps by enforcing it via specialized classes. This can also be enforced by simple convention, ie objects of type foo should never keep ptrs of type bar internally as they do not own them and if they do they cannot assume them always valid and might have to check for validity first. Etc.
If you find this hard to determine, it could be a sign that the code is very complex. Could it be made in a more simple manner?
Understanding how your memory is used and accessed is key to writing clean code for maintenance and performance optimizations. This is true regardless of language used.
Best of luck.
I stumbled upon Stack Overflow question Memory leak with std::string when using std::list<std::string>, and one of the comments says this:
Stop using new so much. I can't see any reason you used new anywhere you did. You can create objects by value in C++ and it's one of the huge advantages to using the language. You do not have to allocate everything on the heap. Stop thinking like a Java programmer.
I'm not really sure what he means by that.
Why should objects be created by value in C++ as often as possible, and what difference does it make internally? Did I misinterpret the answer?
There are two widely-used memory allocation techniques: automatic allocation and dynamic allocation. Commonly, there is a corresponding region of memory for each: the stack and the heap.
Stack
The stack always allocates memory in a sequential fashion. It can do so because it requires you to release the memory in the reverse order (First-In, Last-Out: FILO). This is the memory allocation technique for local variables in many programming languages. It is very, very fast because it requires minimal bookkeeping and the next address to allocate is implicit.
In C++, this is called automatic storage because the storage is claimed automatically at the end of scope. As soon as execution of current code block (delimited using {}) is completed, memory for all variables in that block is automatically collected. This is also the moment where destructors are invoked to clean up resources.
Heap
The heap allows for a more flexible memory allocation mode. Bookkeeping is more complex and allocation is slower. Because there is no implicit release point, you must release the memory manually, using delete or delete[] (free in C). However, the absence of an implicit release point is the key to the heap's flexibility.
Reasons to use dynamic allocation
Even if using the heap is slower and potentially leads to memory leaks or memory fragmentation, there are perfectly good use cases for dynamic allocation, as it's less limited.
Two key reasons to use dynamic allocation:
You don't know how much memory you need at compile time. For instance, when reading a text file into a string, you usually don't know what size the file has, so you can't decide how much memory to allocate until you run the program.
You want to allocate memory which will persist after leaving the current block. For instance, you may want to write a function string readfile(string path) that returns the contents of a file. In this case, even if the stack could hold the entire file contents, you could not return from a function and keep the allocated memory block.
Why dynamic allocation is often unnecessary
In C++ there's a neat construct called a destructor. This mechanism allows you to manage resources by aligning the lifetime of the resource with the lifetime of a variable. This technique is called RAII and is the distinguishing point of C++. It "wraps" resources into objects. std::string is a perfect example. This snippet:
int main ( int argc, char* argv[] )
{
std::string program(argv[0]);
}
actually allocates a variable amount of memory. The std::string object allocates memory using the heap and releases it in its destructor. In this case, you did not need to manually manage any resources and still got the benefits of dynamic memory allocation.
In particular, it implies that in this snippet:
int main ( int argc, char* argv[] )
{
std::string * program = new std::string(argv[0]); // Bad!
delete program;
}
there is unneeded dynamic memory allocation. The program requires more typing (!) and introduces the risk of forgetting to deallocate the memory. It does this with no apparent benefit.
Why you should use automatic storage as often as possible
Basically, the last paragraph sums it up. Using automatic storage as often as possible makes your programs:
faster to type;
faster when run;
less prone to memory/resource leaks.
Bonus points
In the referenced question, there are additional concerns. In particular, the following class:
class Line {
public:
Line();
~Line();
std::string* mString;
};
Line::Line() {
mString = new std::string("foo_bar");
}
Line::~Line() {
delete mString;
}
Is actually a lot more risky to use than the following one:
class Line {
public:
Line();
std::string mString;
};
Line::Line() {
mString = "foo_bar";
// note: there is a cleaner way to write this.
}
The reason is that std::string properly defines a copy constructor. Consider the following program:
int main ()
{
Line l1;
Line l2 = l1;
}
Using the original version, this program will likely crash, as it uses delete on the same string twice. Using the modified version, each Line instance will own its own string instance, each with its own memory and both will be released at the end of the program.
Other notes
Extensive use of RAII is considered a best practice in C++ because of all the reasons above. However, there is an additional benefit which is not immediately obvious. Basically, it's better than the sum of its parts. The whole mechanism composes. It scales.
If you use the Line class as a building block:
class Table
{
Line borders[4];
};
Then
int main ()
{
Table table;
}
allocates four std::string instances, four Line instances, one Table instance and all the string's contents and everything is freed automagically.
Because the stack is faster and leak-proof
In C++, it takes but a single instruction to allocate space—on the stack—for every local scope object in a given function, and it's impossible to leak any of that memory. That comment intended (or should have intended) to say something like "use the stack and not the heap".
The reason why is complicated.
First, C++ is not garbage collected. Therefore, for every new, there must be a corresponding delete. If you fail to put this delete in, then you have a memory leak. Now, for a simple case like this:
std::string *someString = new std::string(...);
//Do stuff
delete someString;
This is simple. But what happens if "Do stuff" throws an exception? Oops: memory leak. What happens if "Do stuff" issues return early? Oops: memory leak.
And this is for the simplest case. If you happen to return that string to someone, now they have to delete it. And if they pass it as an argument, does the person receiving it need to delete it? When should they delete it?
Or, you can just do this:
std::string someString(...);
//Do stuff
No delete. The object was created on the "stack", and it will be destroyed once it goes out of scope. You can even return the object, thus transfering its contents to the calling function. You can pass the object to functions (typically as a reference or const-reference: void SomeFunc(std::string &iCanModifyThis, const std::string &iCantModifyThis). And so forth.
All without new and delete. There's no question of who owns the memory or who's responsible for deleting it. If you do:
std::string someString(...);
std::string otherString;
otherString = someString;
It is understood that otherString has a copy of the data of someString. It isn't a pointer; it is a separate object. They may happen to have the same contents, but you can change one without affecting the other:
someString += "More text.";
if(otherString == someString) { /*Will never get here */ }
See the idea?
Objects created by new must be eventually deleted lest they leak. The destructor won't be called, memory won't be freed, the whole bit. Since C++ has no garbage collection, it's a problem.
Objects created by value (i. e. on stack) automatically die when they go out of scope. The destructor call is inserted by the compiler, and the memory is auto-freed upon function return.
Smart pointers like unique_ptr, shared_ptr solve the dangling reference problem, but they require coding discipline and have other potential issues (copyability, reference loops, etc.).
Also, in heavily multithreaded scenarios, new is a point of contention between threads; there can be a performance impact for overusing new. Stack object creation is by definition thread-local, since each thread has its own stack.
The downside of value objects is that they die once the host function returns - you cannot pass a reference to those back to the caller, only by copying, returning or moving by value.
C++ doesn't employ any memory manager by its own. Other languages like C# and Java have a garbage collector to handle the memory
C++ implementations typically use operating system routines to allocate the memory and too much new/delete could fragment the available memory
With any application, if the memory is frequently being used it's advisable to preallocate it and release when not required.
Improper memory management could lead memory leaks and it's really hard to track. So using stack objects within the scope of function is a proven technique
The downside of using stack objects are, it creates multiple copies of objects on returning, passing to functions, etc. However, smart compilers are well aware of these situations and they've been optimized well for performance
It's really tedious in C++ if the memory being allocated and released in two different places. The responsibility for release is always a question and mostly we rely on some commonly accessible pointers, stack objects (maximum possible) and techniques like auto_ptr (RAII objects)
The best thing is that, you've control over the memory and the worst thing is that you will not have any control over the memory if we employ an improper memory management for the application. The crashes caused due to memory corruptions are the nastiest and hard to trace.
I see that a few important reasons for doing as few new's as possible are missed:
Operator new has a non-deterministic execution time
Calling new may or may not cause the OS to allocate a new physical page to your process. This can be quite slow if you do it often. Or it may already have a suitable memory location ready; we don't know. If your program needs to have consistent and predictable execution time (like in a real-time system or game/physics simulation), you need to avoid new in your time-critical loops.
Operator new is an implicit thread synchronization
Yes, you heard me. Your OS needs to make sure your page tables are consistent and as such calling new will cause your thread to acquire an implicit mutex lock. If you are consistently calling new from many threads you are actually serialising your threads (I've done this with 32 CPUs, each hitting on new to get a few hundred bytes each, ouch! That was a royal p.i.t.a. to debug.)
The rest, such as slow, fragmentation, error prone, etc., have already been mentioned by other answers.
Pre-C++17:
Because it is prone to subtle leaks even if you wrap the result in a smart pointer.
Consider a "careful" user who remembers to wrap objects in smart pointers:
foo(shared_ptr<T1>(new T1()), shared_ptr<T2>(new T2()));
This code is dangerous because there is no guarantee that either shared_ptr is constructed before either T1 or T2. Hence, if one of new T1() or new T2() fails after the other succeeds, then the first object will be leaked because no shared_ptr exists to destroy and deallocate it.
Solution: use make_shared.
Post-C++17:
This is no longer a problem: C++17 imposes a constraint on the order of these operations, in this case ensuring that each call to new() must be immediately followed by the construction of the corresponding smart pointer, with no other operation in between. This implies that, by the time the second new() is called, it is guaranteed that the first object has already been wrapped in its smart pointer, thus preventing any leaks in case an exception is thrown.
A more detailed explanation of the new evaluation order introduced by C++17 was provided by Barry in another answer.
Thanks to #Remy Lebeau for pointing out that this is still a problem under C++17 (although less so): the shared_ptr constructor can fail to allocate its control block and throw, in which case the pointer passed to it is not deleted.
Solution: use make_shared.
To a great extent, that's someone elevating their own weaknesses to a general rule. There's nothing wrong per se with creating objects using the new operator. What there is some argument for is that you have to do so with some discipline: if you create an object you need to make sure it's going to be destroyed.
The easiest way of doing that is to create the object in automatic storage, so C++ knows to destroy it when it goes out of scope:
{
File foo = File("foo.dat");
// Do things
}
Now, observe that when you fall off that block after the end-brace, foo is out of scope. C++ will call its destructor automatically for you. Unlike Java, you don't need to wait for the garbage collection to find it.
Had you written
{
File * foo = new File("foo.dat");
you would want to match it explicitly with
delete foo;
}
or even better, allocate your File * as a "smart pointer". If you aren't careful about that it can lead to leaks.
The answer itself makes the mistaken assumption that if you don't use new you don't allocate on the heap; in fact, in C++ you don't know that. At most, you know that a small amount of memory, say one pointer, is certainly allocated on the stack. However, consider if the implementation of File is something like:
class File {
private:
FileImpl * fd;
public:
File(String fn){ fd = new FileImpl(fn);}
Then FileImpl will still be allocated on the stack.
And yes, you'd better be sure to have
~File(){ delete fd ; }
in the class as well; without it, you'll leak memory from the heap even if you didn't apparently allocate on the heap at all.
new() shouldn't be used as little as possible. It should be used as carefully as possible. And it should be used as often as necessary as dictated by pragmatism.
Allocation of objects on the stack, relying on their implicit destruction, is a simple model. If the required scope of an object fits that model then there's no need to use new(), with the associated delete() and checking of NULL pointers.
In the case where you have lots of short-lived objects allocation on the stack should reduce the problems of heap fragmentation.
However, if the lifetime of your object needs to extend beyond the current scope then new() is the right answer. Just make sure that you pay attention to when and how you call delete() and the possibilities of NULL pointers, using deleted objects and all of the other gotchas that come with the use of pointers.
When you use new, objects are allocated to the heap. It is generally used when you anticipate expansion. When you declare an object such as,
Class var;
it is placed on the stack.
You will always have to call destroy on the object that you placed on the heap with new. This opens the potential for memory leaks. Objects placed on the stack are not prone to memory leaking!
One notable reason to avoid overusing the heap is for performance -- specifically involving the performance of the default memory management mechanism used by C++. While allocation can be quite quick in the trivial case, doing a lot of new and delete on objects of non-uniform size without strict order leads not only to memory fragmentation, but it also complicates the allocation algorithm and can absolutely destroy performance in certain cases.
That's the problem that memory pools where created to solve, allowing to to mitigate the inherent disadvantages of traditional heap implementations, while still allowing you to use the heap as necessary.
Better still, though, to avoid the problem altogether. If you can put it on the stack, then do so.
I tend to disagree with the idea of using new "too much". Though the original poster's use of new with system classes is a bit ridiculous. (int *i; i = new int[9999];? really? int i[9999]; is much clearer.) I think that is what was getting the commenter's goat.
When you're working with system objects, it's very rare that you'd need more than one reference to the exact same object. As long as the value is the same, that's all that matters. And system objects don't typically take up much space in memory. (one byte per character, in a string). And if they do, the libraries should be designed to take that memory management into account (if they're written well). In these cases, (all but one or two of the news in his code), new is practically pointless and only serves to introduce confusions and potential for bugs.
When you're working with your own classes/objects, however (e.g. the original poster's Line class), then you have to begin thinking about the issues like memory footprint, persistence of data, etc. yourself. At this point, allowing multiple references to the same value is invaluable - it allows for constructs like linked lists, dictionaries, and graphs, where multiple variables need to not only have the same value, but reference the exact same object in memory. However, the Line class doesn't have any of those requirements. So the original poster's code actually has absolutely no needs for new.
I think the poster meant to say You do not have to allocate everything on the heap rather than the the stack.
Basically, objects are allocated on the stack (if the object size allows, of course) because of the cheap cost of stack-allocation, rather than heap-based allocation which involves quite some work by the allocator, and adds verbosity because then you have to manage data allocated on the heap.
Two reasons:
It's unnecessary in this case. You're making your code needlessly more complicated.
It allocates space on the heap, and it means that you have to remember to delete it later, or it will cause a memory leak.
Many answers have gone into various performance considerations. I want to address the comment which puzzled OP:
Stop thinking like a Java programmer.
Indeed, in Java, as explained in the answer to this question,
You use the new keyword when an object is being explicitly created for the first time.
but in C++, objects of type T are created like so: T{} (or T{ctor_argument1,ctor_arg2} for a constructor with arguments). That's why usually you just have no reason to want to use new.
So, why is it ever used at all? Well, for two reasons:
You need to create many values the number of which is not known at compile time.
Due to limitations of the C++ implementation on common machines - to prevent a stack overflow by allocating too much space creating values the regular way.
Now, beyond what the comment you quoted implied, you should note that even those two cases above are covered well enough without you having to "resort" to using new yourself:
You can use container types from the standard libraries which can hold a runtime-variable number of elements (like std::vector).
You can use smart pointers, which give you a pointer similar to new, but ensure that memory gets released where the "pointer" goes out of scope.
and for this reason, it is an official item in the C++ community Coding Guidelines to avoid explicit new and delete: Guideline R.11.
The core reason is that objects on heap are always difficult to use and manage than simple values. Writing code that are easy to read and maintain is always the first priority of any serious programmer.
Another scenario is the library we are using provides value semantics and make dynamic allocation unnecessary. Std::string is a good example.
For object oriented code however, using a pointer - which means use new to create it beforehand - is a must. In order to simplify the complexity of resource management, we have dozens of tools to make it as simple as possible, such as smart pointers. The object based paradigm or generic paradigm assumes value semantics and requires less or no new, just as the posters elsewhere stated.
Traditional design patterns, especially those mentioned in GoF book, use new a lot, as they are typical OO code.
new is the new goto.
Recall why goto is so reviled: while it is a powerful, low-level tool for flow control, people often used it in unnecessarily complicated ways that made code difficult to follow. Furthermore, the most useful and easiest to read patterns were encoded in structured programming statements (e.g. for or while); the ultimate effect is that the code where goto is the appropriate way to is rather rare, if you are tempted to write goto, you're probably doing things badly (unless you really know what you're doing).
new is similar — it is often used to make things unnecessarily complicated and harder to read, and the most useful usage patterns can be encoded have been encoded into various classes. Furthermore, if you need to use any new usage patterns for which there aren't already standard classes, you can write your own classes that encode them!
I would even argue that new is worse than goto, due to the need to pair new and delete statements.
Like goto, if you ever think you need to use new, you are probably doing things badly — especially if you are doing so outside of the implementation of a class whose purpose in life is to encapsulate whatever dynamic allocations you need to do.
One more point to all the above correct answers, it depends on what sort of programming you are doing. Kernel developing in Windows for example -> The stack is severely limited and you might not be able to take page faults like in user mode.
In such environments, new, or C-like API calls are prefered and even required.
Of course, this is merely an exception to the rule.
new allocates objects on the heap. Otherwise, objects are allocated on the stack. Look up the difference between the two.
I'm modifying some C++ source code and I've noticed the author really went out of their way to allocate everything on the stack. Most likely for the deallocation benefits (are there any performance benefits as well??).
I want to keep the same consistency but I need to create a large array of objects and something like:
Object os[1000] = {Object(arg), Object(arg), ....};
isn't going to cut it. Searching around it seems like a way around this is just:
vector<Object> os(1000, Object(arg));
This still allocates on the heap but deallocates like a stack (from what I've read in other posts). I'm just wondering are there any other options because this just seems like a syntax issue. Perhaps a clever #define people know.
The stack shouldn't be used for large blocks of memory. You simply have to pay the higher price of heap allocation in exchange for the benefit of accessing more memory. Another option is declaring an array with static storage duration, but that has other drawbacks (not re-entrant, not thread-safe). Everything is a tradeoff.
In any case, when allocating complex objects, the cost of calling 1000 constructors will dwarf the time spent in the allocator. Just use std::vector unless you have profiler data that shows a performance problem.
Yes, there are other options. You can use something like alloca. This will get you stack allocation and automatic free, but not automatic construction or destruction. You would need to use placement new and explicit invocation of the destructors.
Yes, there may be a performance advantage, but you're also begging to blow the stack, and this pattern is not exception safe like the vector solution would be (that is, if the object your allocating has a non-trivial destructor).
Allocating large amounts of data on the stack is, generally speaking, a bad idea. The stack on most operating systems is a scratch space and fairly limited in size. Allocating a large amount of stack space for objects can quickly consume all your available stack space, resulting in a segfault or other exception when something attempts to allocate just one more thing on the stack (for instance, a return address for a function call).
As far as other options, you have a few.. std::vector as you've already noticed, along with boost::array are to such examples.
This ought to work:
Object os[1000];
os[0] = Object(args);
std::copy(os, os + 999, os + 1);
This creates the array, initializes one object, then loops through, initializing each element with the last one.
Of course, you probably shouldn't use this. It seems like a bad idea even if it works, and even if Object os[1000] doesn't cause you problems.
I know this will sound weird but i need my app to run fast and it does a lot of new and delete. All function calls new and passes the ptr back expect for the ones pushing a pointer to a list or deque.
At the end of the main loop the program goes across all of that memory and deletes it (unless i forgot to delete it). I am not exaggerating. Is there a mode that allows my code to allocate objs for new but doesnt delete them on delete but just mark it as unused so the next new for that struct will use it instead of doing a full allocation?
I imagine that would boost performance. It isnt fully done so i cant benchmark but i am sure i'd see a boost and if this was automatic then great. Is there such a mode or flag i can use?
I am using gcc (linux, win) and MSVC2010(win).
Try object pooling via Boost - http://www.boost.org/doc/libs/1_44_0/libs/pool/doc/index.html
What do you mean by "end of the main loop" - after the loop finishes, or just before it repeats?
If the former, then you can safely leave memory allocated when your process exits, although it isn't recommended. The OS will recover it, probably faster than you'd do by deleting each object. Destructors won't be called (so if they do anything important other than freeing resources associated with the process, then don't do this). Debugging tools will tell you that you have memory leaks, which isn't very satisfactory, but it works on the OSes you name.
If the latter, then "marking the memory unused so that the next new will use it" is exactly what delete does (well, after destructors). Some special-purpose memory allocators are faster than general-purpose allocators, though. You could try using a memory pool allocator instead of the default new/delete, if you have a lot of objects of the same size.
"I imagine that would boost performance"
Unfortunately we can't get performance boosts just by imagining them ;-p Write the code first, measure performance, then worry about changing your allocation once you know what you're up against. "Faster" is pretty much useless if the boring, simple version of your code is already "easily fast enough". You can usually change your allocation mechanism without significant changes to the rest of your code, so you don't have to worry about it in up-front design.
What your are describing is what malloc and co usually do, keeping memory around and reallocating it for similar sized allocations.
i believe what you are looking for is a "placement new".
Use new to allocate byte size memory only once.
And later on just use the ptr as follows
Type* ptr = static_cast<Type*>(operator new (sizeof(Type))); // need to call only once and store the pointer
Type* next_ptr = new (ptr) Type();
Manually call the destructors instead of delete.
next_ptr->~Type();
Since no memory allocation happens this should definitely be fast. "how fast" i am not sure
Using a memory pool is what you are looking to achieve.
You also could use a few of the windows Heap allocation methods, and instead of just free'ing each individual allocation, you could just free the entire heap all at once. Though if you are using a memory profiling tool (like bounds checker) it will think it's a problem.