Like Tree5Likes
  • 1 Post By antred
  • 1 Post By manasij7479
  • 1 Post By manasij7479
  • 1 Post By laserlight

New operator

This is a discussion on New operator within the C++ Programming forums, part of the General Programming Boards category; Don't really understand what the new operator does. My books say it's a memory allocation operator which makes perfect sense, ...

  1. #1
    Registered User ex-mortis's Avatar
    Join Date
    Mar 2012
    Posts
    37

    New operator

    Don't really understand what the new operator does. My books say it's a memory allocation operator which makes perfect sense, but does it simply free up memory to store a placeholder for a pointer? If so, what is the usefulness of reserving memory instead of just initializing a pointer and thus using the necessary amount of memory? What is the essential difference between:

    Code:
    int x = 100;
    int *p = &x;
    //do stuff
    delete p;
    and

    Code:
    int x = 100;
    int *p = new int; //really not too sure about this syntax, do you need to specify the type of the pointer when using new?
    //…
    *p = &x;
    //do stuff
    delete p;
    If your program needs pointers to hold memory addresses, why don't you just initialize the pointers when they are needed? Maybe I just have no idea what new does.
    Last edited by ex-mortis; 06-16-2012 at 06:50 AM.

  2. #2
    Registered User manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    Kolkata@India
    Posts
    2,498
    The new operator allocates objects on the heap (1) which exists as long as you don't call delete, while a normal object is allocated on the stack (2), which is destructed on scope exit.
    Code:
    int* foo() //(2)
    {
        int x = 100;
        return &x; //Undefined behaviour, as x does not exist after the function exits
    }
    
    int* foo()//(1)
    {
        int * x = new int(100);
        return x;//Okay, but you *must* call delete after you are done with the return value.
    }
    Also, stack space is very limited on normal computers, while the heap has all (not really, read up on virtual memory if you want details) the free memory in your RAM.
    Last edited by manasij7479; 06-16-2012 at 06:57 AM.
    Manasij Mukherjee | gcc-4.8.2 @Arch Linux
    Slow and Steady wins the race... if and only if :
    1.None of the other participants are fast and steady.
    2.The fast and unsteady suddenly falls asleep while running !



  3. #3
    Registered User ex-mortis's Avatar
    Join Date
    Mar 2012
    Posts
    37
    Quote Originally Posted by manasij7479 View Post
    The new operator allocates objects on the heap (1) which exists as long as you don't call delete, while a normal object is allocated on the stack (2), which is destructed on scope exit.
    Code:
    int* foo() //(2)
    {
        int x = 100;
        return &x; //Undefined behaviour, as x does not exist after the function exits
    }
    
    int* foo()//(1)
    {
        int * x = new int(100);
        return x;//Okay, but you *must* call delete after you are done with the return value.
    }
    Also, stack space is very limited on normal computers, while the heap has all (not really, read up on virtual memory if you want details) the free memory in your RAM.
    Thanks for the quick reply. Surprisingly, I think I fully understand now (actually I didn't know the difference between heap and stack memory, but I do now). Right now I'm reading through Effective C++, just read the Item called "Don't try to return a reference when you must return an object" yesterday, so I understand how returning the memory address of a local variable doesn't work.

    Does new have any use in the global scope though?

  4. #4
    Registered User manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    Kolkata@India
    Posts
    2,498
    Of course it has, it dynamically allocates memory (as much as you need) !
    Manasij Mukherjee | gcc-4.8.2 @Arch Linux
    Slow and Steady wins the race... if and only if :
    1.None of the other participants are fast and steady.
    2.The fast and unsteady suddenly falls asleep while running !



  5. #5
    Registered User antred's Avatar
    Join Date
    Apr 2012
    Location
    Germany
    Posts
    227
    But also know that new should be used sparingly and only when really necessary. For one, pointer semantics are a lot less convenient and more error prone than value semantics (smart pointers alleviate that pain to some degree). Also, in multi-threaded applications there may be certain performance issues attached to the use of new. The free store from which new gets memory has to be protected from concurrent access, which means some sort of locking may be involved. This can potentially hurt performance.
    manasij7479 likes this.

  6. #6
    Registered User ex-mortis's Avatar
    Join Date
    Mar 2012
    Posts
    37
    Quote Originally Posted by manasij7479 View Post
    Of course it has, it dynamically allocates memory (as much as you need) !
    This is where I get confused. Dynamically allocates it for what? If you need to hold the memory address of an object, won't you just initialize a pointer or make a reference to it? What does blank allocated memory exactly do? I realize it is not truly blank, because the 2/4/6/whatever bytes of data are already reserved, but there is no data there, right?

    semi-EDIT: I understand that there actually is data there, as I misunderstood the fundamental use of new (I thought it reserved memory instead of writing data to it). But instead of deleting the post I'm gonna leave it out there just in case I don't understand (which is not unlikely).

    Quote Originally Posted by antred View Post
    But also know that new should be used sparingly and only when really necessary. For one, pointer semantics are a lot less convenient and more error prone than value semantics (smart pointers alleviate that pain to some degree). Also, in multi-threaded applications there may be certain performance issues attached to the use of new. The free store from which new gets memory has to be protected from concurrent access, which means some sort of locking may be involved. This can potentially hurt performance.
    Yeah, this is not going to become my new favorite C++ thing or anything, I just wasn't sure about it and wanted to learn. About the second part, why would there be locking involved in multi-threaded applications and not in single-threaded ones (if you know)?
    Last edited by ex-mortis; 06-16-2012 at 07:35 AM.

  7. #7
    Registered User antred's Avatar
    Join Date
    Apr 2012
    Location
    Germany
    Posts
    227
    Quote Originally Posted by ex-mortis View Post
    Yeah, this is not going to become my new favorite C++ thing or anything, I just wasn't sure about it and wanted to learn. About the second part, why would there be locking involved in multi-threaded applications and not in single-threaded ones (if you know)?
    I can't really give you a general answer to that as a lot of it depends on the compiler / operating system used, but apparently on Windows, EVERY access to the free store involves a lock (even in single-threaded applications, if I understand correctly ... though I'm by no means sure about that one). Maybe someone more knowledgeable than myself can clear that up.

    In the meantime, here's a link to a StackOverflow question related to this topic. multithreading - In multithreaded C/C++, does malloc/new lock the heap when allocating memory - Stack Overflow

  8. #8
    Registered User manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    Kolkata@India
    Posts
    2,498
    Quote Originally Posted by ex-mortis View Post
    This is where I get confused. Dynamically allocates it for what? If you need to hold the memory address of an object, won't you just initialize a pointer or make a reference to it? What does blank allocated memory exactly do? I realize it is not truly blank, because the 2/4/6/whatever bytes of data are already reserved, but there is no data there, right?

    semi-EDIT: I understand that there actually is data there, as I misunderstood the fundamental use of new (I thought it reserved memory instead of writing data to it). But instead of deleting the post I'm gonna leave it out there just in case I don't understand (which is not unlikely).
    The memory allocated by new contains a full constructed object of the type you have specified (here, int and it'll contain 0);

    Yeah, this is not going to become my new favorite C++ thing or anything, I just wasn't sure about it and wanted to learn.
    yes, learn to use the standard containers.

    About the second part, why would there be locking involved in multi-threaded applications and not in single-threaded ones (if you know)?
    When you go to a public restroom, do you lock the door?
    You can, of course do the same when you are alone at your home, but that doesn't serve any purpose.
    antred likes this.
    Manasij Mukherjee | gcc-4.8.2 @Arch Linux
    Slow and Steady wins the race... if and only if :
    1.None of the other participants are fast and steady.
    2.The fast and unsteady suddenly falls asleep while running !



  9. #9
    Registered User antred's Avatar
    Join Date
    Apr 2012
    Location
    Germany
    Posts
    227
    Quote Originally Posted by manasij7479 View Post
    When you go to a public restroom, do you lock the door?
    You can, of course do the same when you are alone at your home, but that doesn't serve any purpose.
    LOL, that's a great analogy. I'll use that the next time this question comes up.

  10. #10
    Registered User manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    Kolkata@India
    Posts
    2,498
    Quote Originally Posted by antred View Post
    LOL, that's a great analogy. I'll use that the next time this question comes up.
    Just wait till grumpy says that a public toilet can't protect itself from concurrent access !

    (The analogy actually still holds up!)
    iMalc likes this.
    Manasij Mukherjee | gcc-4.8.2 @Arch Linux
    Slow and Steady wins the race... if and only if :
    1.None of the other participants are fast and steady.
    2.The fast and unsteady suddenly falls asleep while running !



  11. #11
    Registered User ex-mortis's Avatar
    Join Date
    Mar 2012
    Posts
    37
    Quote Originally Posted by manasij7479 View Post
    When you go to a public restroom, do you lock the door?
    You can, of course do the same when you are alone at your home, but that doesn't serve any purpose.
    Get it, thanks.

    Quote Originally Posted by manasij7479 View Post
    yes, learn to use the standard containers.
    This line confuses me greatly. Really don't know if it's sarcastic or not. If you mean I should prefer the standard types for holding data to pointers, then I already do because I know they can be dangerous and I only use them if necessary. But you said I should learn to use the standard containers. What do you mean by that?

  12. #12
    Registered User manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    Kolkata@India
    Posts
    2,498
    :facepalm:
    By standard containers. I mean std::vector, std::string, std::list. std::deque, std::map, etc.
    They greatly simplify the task of high level programming, and frees the programmer of having to deal with memory management (new-delete) directly.
    Last edited by manasij7479; 06-16-2012 at 08:35 AM.
    Manasij Mukherjee | gcc-4.8.2 @Arch Linux
    Slow and Steady wins the race... if and only if :
    1.None of the other participants are fast and steady.
    2.The fast and unsteady suddenly falls asleep while running !



  13. #13
    Registered User ex-mortis's Avatar
    Join Date
    Mar 2012
    Posts
    37
    Quote Originally Posted by manasij7479 View Post
    :facepalm:
    By standard containers. I mean std::vector, std::string, std::list. std::deque, std::map, etc.
    They greatly simplify the task of high level programming, and frees the programmer of having to deal with memory management (new-delete) directly.
    Alright I'll read up on them, thanks.

  14. #14
    Registered User R41D3N's Avatar
    Join Date
    Mar 2012
    Location
    ...Beyond Infinity, Behind a KeyBoard...
    Posts
    29
    Just to clarify, he meant the Standard Template Library (STL) part of C++, wherein you dont have to "new-delete" stuff and can have dynamic size even during run-time

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,451
    Part of this thread was moved to a thread specifically about the STL.
    R41D3N likes this.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

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, 09:21 AM
  3. Replies: 3
    Last Post: 12-09-2008, 10:19 AM
  4. Replies: 2
    Last Post: 07-07-2008, 03:46 AM
  5. Replies: 1
    Last Post: 07-07-2008, 03:38 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21