I know that operator new allocates memory, but when should i use it?
what is the difference between this?
and this?Code:MyClass class;
Code:MyClass class = new MyClass();
Printable View
I know that operator new allocates memory, but when should i use it?
what is the difference between this?
and this?Code:MyClass class;
Code:MyClass class = new MyClass();
No difference: they both would result in a compile error since class is a reserved word.
If you changed the first one to:
then it declares an object named x of type MyClass.Code:MyClass x;
This:
would still be a compile error, but you could write:Code:MyClass x = new MyClass();
Though it would be better to use a smart pointer instead.Code:MyClass* x = new MyClass();
Well i should created other object name, not class. But got idea.
So basically i need pointer to point to that new object i created?
Yes, but as I mentioned, if you really do need to do this, then it would be better to use a smart pointer, e.g., #include <memory> and write:
otherwise, you need to remember to have a delete match the new.Code:std::unique_ptr<MyClass> x(new MyClass());
One allocates data on the stack and one allocates memory on the heap.
For stack info : Call stack - Wikipedia, the free encyclopedia
As for the "heap", it's what happens when make an explicit request for memory in a program. You call new() or malloc() which then makes a request from the underlying OS/kernel for a section of memory of a specific size. It then returns the address of that memory. The heap is all the RAM that's not the stack. It's up to your OS to determine how memory requests should be handled because, obviously, more than one program is using the system's RAM at a time. Here's some good info : Memory management - Wikipedia, the free encyclopedia
There's also placement new() which is neat. If you feed new() an address, you will not allocate an object in memory (no kernel requests) but still instead construct the class at the specified location. You can also destruct the objects as well in-place. Here's a link : What is "placement new" and why would I use it?, C++ FAQ
The stack is, in general, much faster than the heap because there's no waiting on the kernel to resolve acceptable addresses for allocations. But you then run the danger of writing beyond the stack which will crash your program.
Heap allocations can be slow but they're convenient for prototyping. One common tactic is to limit the number of explicit new()/malloc() calls by allocating one large contiguous chunk of memory and then managing allocations/deallocations on it yourself.
Not all programs can easily be solved with just one contiguous chunk of memory. std::vector is contiguous but std::list is not.
Writing beyond the extent of any allocated memory can crash your program. It doesn't matter if that memory is categorised as heap, stack, virtual, physical, or anything else. Similarly, it doesn't matter if that memory is allocated statically, dynamically, automatically, or in any other way.
I may want to use "new" operator in cases of:
1) to manage myself what is the lifetime of an object :
Objects which created without new (on the stack) , are created the moment they are declared and their constructor is called. they are automatically destroyed when the function which created them are done . with "new" , objects are created the moment I used "new" + constructor and destroyed the moment I call "delete" (which calls the destructor first)
2) to manage myself the scope of the object:
(generally speaking) as long as "delete" wasn't called on a dynamic allocated object - anyone who keeps a pointer to the object can use it . this is not the case when allocating objects without new - you must think when will the object be destroyed and the pointer to it gets invalid (for example, return a pointer of local object of a function will cause an error , known as "Segmentation fault").
3) when an object contains or point to another object , but the inner/pointed object should not be created yet:
in other words - to have full control WHEN to create an object
for example, linked list / trees - I don't know when another nodes will be appended to the linked list , I want to keep the option to point another object .
for this purpose I keep a pointer to the next node and when I need to append a new node - I use new
interesting use of new operator comes when needing to parse some text to data structure , for example XML and JSON. we don't know what will the xml or json will look like, or what order they'll have inside them. we just start with some map-like object , keeping some pointers inside of it and appending them new elements while parsing (using new).
the point is that when we want create element dynamically (e.g. we don't know exactly how will the object looks like 100% on compilation time) we use new.
4) in a multi-threaded environment:
In order to make an object accessible from multiple threads , and to avoid stack-allocating problems (see 1 and 2) , we allocate an object with new .
this makes it accessible to many threads without worrying about the object being destroyed automatically.
5) in some design patterns :
like Single-Tone and Factory . google it.
6) in order to prevent multiple copies of heavy objects:
let's consider the following semi-pseudocode:
in this code , there are few copying action preformedCode:
string getTextFromFile(string filePath){
someFileStreamer filereader(filePath);
return fileReader.readAll(); //readAll returns a string
}
void anotherFunction(){
string fileContent = getTextFromFile(..)
}
a) inside readTextFromFile - readAll result is copied to the return value.
b) the return value is again copied inside anotherFunction to fileContent.
all good , but what if the file actually weight 3 megabytes? such copy is very very heavy. we can save many copyes by allocating a new string , and return pointer rather than a copy :
now we reduced 2 excess copies to 1. (wher new string(..) is created);Code:
string& getTextFromFile(string filePath){
someFileStreamer filereader(filePath);
return *new string(fileReader.readAll()); //readAll returns a string
}
void anotherFunction(){
string& fileContent = getTextFromFile(..)
}
interesting anecdote:
because c and c++ compiles entirely to assembly code, that gives us the privilege to allocated objects without "new" operator. that because that when a program compiles - it compiles directly to the operating system environment. that why C and C++ are called "Native" - they talk directly to the operating system in it's own language .
other managed languages , like Java and C# , are managed one. because the code basically is interpreted and not compiles to assembly - all the objects has to be allocated with "new" , since everything is happening at runtime.
where you want to give memory u will use new keyword . When object is created u must give the memory to data member and member function . You need to allocated memory for that object first .