Thread: avoiding new

  1. #1
    Banned
    Join Date
    Nov 2007
    Posts
    678

    avoiding new

    Code:
    class myclass
    {
       int a;
    };
    
    void f()
    {
    // What's the difference between both object creation.
    // Which one is better/safer?
        myclass* obj1 = new myclass;
        myclass obj2;
    }

  2. #2
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    This stuff should be covered by your C++ book, not answered in a forum.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Avoiding new is "better" in the sense that it's automatically deleted when you exit the function. This is also the drawback. Consider the following:
    Code:
    class myclass
    {
    public:
       myclass(int n) : a(n) {};
        ~myclass() { a = -1 };
       int a;
    };
    
    myclass *f(int x)
    {
        myclass obj2(x);
    
        return &obj2;
    }
    
    int main() 
    {
        myclass *obj = f(12)
        std::cout << "obj->a = " << obj->a << std::endl;
    }
    Since you are returning the obj2 that is local to function f, it will then be destroyed, and the value of a is now -1 [assuming nothing has overwritten the location, since it's now freely available to other functions].

    In this case, you _NEED_ to use new or the program will not work correctly.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  4. #4
    Banned
    Join Date
    Nov 2007
    Posts
    678
    Code:
    // Can I not use static in that case?
    
    myclass f()
    {
        static myclass o;
        return o;
    }

  5. #5
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by manav View Post
    Code:
    // Can I not use static in that case?
    
    myclass f()
    {
        static myclass o;
        return o;
    }
    Sure, you can. Note however the above code is actually safe anyways, as it's creating a copy of the object o. So even without static, it would create a copy of o that is external to f. If you have myclass *f() and return &o then it would not create a copy.

    But then you essentially have a global variable [but only accessible by calling f()], which may not be what you wanted.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  6. #6
    Banned
    Join Date
    Nov 2007
    Posts
    678
    Code:
    // Then I think this is better?
    
    myclass& f()
    {
        static myclass o;
        return o;
    }

  7. #7
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by manav View Post
    Code:
    // Then I think this is better?
    
    myclass& f()
    {
        static myclass o;
        return o;
    }
    Better than what?

    What I was trying to point out was that there are situations where you can't avoid using new. There are MANY cases where you can. In this case, you are still using ONE instance of myclass, so every call to f() will use the same myclass instance - it is the same as having one global variable, the only (slight) difference is that it's not visible, you have to call f() to get to it.

    An example of where you [most likely] can't avoid using new is if you use linked lists or binary trees. This is just one of many examples where you may want to "create an object and let it live past the call of this function and not have just one single instance".

    If "new" wasn't necessary in the C++ language, then it wouldn't be there. You can sometimes avoid using new, but it's almost impossible to write a LARGE program without using it at least sometimes.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  8. #8
    Banned
    Join Date
    Nov 2007
    Posts
    678
    Thanks!
    I just got carried away with the idea: "I will avoid new in all my code."
    Now I suspect, if this is possible?
    Last edited by manav; 01-03-2008 at 07:50 AM.

  9. #9
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by manav View Post
    Thanks!
    I just got carried away with the idea: "I will avoid new in all my code."
    Now I suspect this is not possible
    It very much depends on what your program does - but I'd say that if your program is sufficiently complex, it's unlikely to be "right" to do that.

    Tying in with another recent thread, you also need to watch out for stack overflows. They tend to crash your program in a much nastier way [and much sooner] than running out of free-store [where "new" gets it's memory from]. If you create all your storage as local variables in functions, then you will use up more stack-space than you do if you use new to create your objects.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  10. #10
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Don't be afraid of new. In C++, there are many ways to make resource acquisition and destruction automatic. Consider using smart pointers. They'll delete the memory automatically when it's no longer used, so you don't have to worry about it.
    Also avoid static variables since they'll just turn up the same as global variables, mostly. And from what I know, that space isn't unlimited. Or it may be. But in any case, it usually defies implementation rules to use it time and time again. Static was designed so the value of a variable would be the same no matter how many times a function was called.
    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.

  11. #11
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> Which one is better/safer?
    The local object is better/safer than the dynamically allocated one.

    There will be times where you will need dynamic memory, and in those cases you can use new (preferably wrapped in a smart pointer of some kind).

    However, when both will work equally well, prefer the local object.

    >> This stuff should be covered by your C++ book, not answered in a forum.
    I don't believe many C++ books cover this question very well, if they do at all.

  12. #12
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Quote Originally Posted by manav View Post
    Thanks!
    I just got carried away with the idea: "I will avoid new in all my code."
    Now I suspect, if this is possible?
    matsp is pointing out that dynamic memory allocation is unavoidable, even in simple cases.

    However, avoiding new doesn't necessarily mean that you avoid dynamic memory. It could be taken to mean that you should avoid the key word in favor of using containers that manage memory for you. There are many implementations out there of virtually every useful container, so there is little need to write your own. Similarly there are various smart pointer types that can be used to ensure that a single dynamically allocated object will be destroyed when it is no longer needed so there is no need for you to manually delete the object. With these tools you will rarely see calls to new and especially delete in your code.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  13. #13
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Simple: Don't use 'new' if you don't need to.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  14. #14
    Banned
    Join Date
    Nov 2007
    Posts
    678
    Thank you all for those comments!
    I found many ways (in those comments) to avoid dealing with memory management (hence avoiding new also).

  15. #15
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by iMalc View Post
    Simple: Don't use 'new' if you don't need to.
    As usual, iMalc summarizes the overall subject very well - I tend to ramble and explain too many things from time to time...

    I completely agree with the above statement, as well as Daved's comments.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Avoiding Global variables
    By csonx_p in forum Windows Programming
    Replies: 32
    Last Post: 05-19-2008, 12:17 AM
  2. Avoiding multiple includes
    By plan7 in forum C Programming
    Replies: 5
    Last Post: 11-25-2007, 06:13 AM
  3. Avoiding 'GOTO' - Help with some code
    By 3saul in forum C Programming
    Replies: 7
    Last Post: 04-01-2006, 12:34 AM
  4. Avoiding Page File
    By Smartiepants586 in forum C Programming
    Replies: 3
    Last Post: 06-08-2005, 10:55 AM
  5. Avoiding leaks on dynamically created data members
    By Mario in forum C++ Programming
    Replies: 13
    Last Post: 06-01-2002, 11:31 PM