Thread: operator new

  1. #1
    Registered User
    Join Date
    Apr 2013
    Posts
    34

    operator new

    I know that operator new allocates memory, but when should i use it?

    what is the difference between this?
    Code:
    MyClass class;
    and this?

    Code:
    MyClass class = new MyClass();

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    No difference: they both would result in a compile error since class is a reserved word.

    If you changed the first one to:
    Code:
    MyClass x;
    then it declares an object named x of type MyClass.

    This:
    Code:
    MyClass x = new MyClass();
    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.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Apr 2013
    Posts
    34
    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?

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    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:
    Code:
    std::unique_ptr<MyClass> x(new MyClass());
    otherwise, you need to remember to have a delete match the new.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Quote Originally Posted by Aeoskype View Post
    I know that operator new allocates memory, but when should i use it?

    what is the difference between this?
    Code:
    MyClass class;
    and this?

    Code:
    MyClass class = 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.
    Last edited by MutantJohn; 01-22-2015 at 12:41 PM.

  6. #6
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by MutantJohn View Post
    But you then run the danger of writing beyond the stack which will crash your program.
    Writing beyond the end of your allocated heap memory can crash your program too.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #7
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    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.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  8. #8
    Registered User
    Join Date
    Dec 2013
    Posts
    241
    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:
    Code:
    string getTextFromFile(string filePath){
    someFileStreamer filereader(filePath);
    return fileReader.readAll(); //readAll returns a string
    }
    
    void anotherFunction(){
    string fileContent = getTextFromFile(..)
    }
    in this code , there are few copying action preformed
    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 :

    Code:
    string& getTextFromFile(string filePath){
    someFileStreamer filereader(filePath);
    return *new string(fileReader.readAll()); //readAll returns a string
    }
    
    void anotherFunction(){
    string& fileContent = getTextFromFile(..)
    }
    now we reduced 2 excess copies to 1. (wher new string(..) is created);

    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.
    Last edited by Dave11; 01-23-2015 at 04:44 AM.

  9. #9
    Registered User
    Join Date
    Jan 2015
    Posts
    1
    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 .

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Ternary Operator to choose which operator to use
    By cncool in forum C Programming
    Replies: 7
    Last Post: 06-27-2011, 01:35 PM
  2. [ ] operator requires + operator?
    By m37h0d in forum C++ Programming
    Replies: 10
    Last Post: 02-04-2009, 10:21 AM
  3. Replies: 3
    Last Post: 12-09-2008, 11:19 AM
  4. Replies: 2
    Last Post: 07-07-2008, 03:46 AM
  5. Replies: 1
    Last Post: 07-07-2008, 03:38 AM