CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 25
  1. #1
    Join Date
    Jul 2008
    Posts
    32

    Declare class pointer with or without new

    Hi all,

    What are the disadvantages to declaring a C++ class pointer without the new operator? E.g. situation 1:

    Code:
    MyClass* myClass;
    Situation 2:

    Code:
    MyClass* myClass = new MyClass();
    I understand that using the new operator declares the object on the heap instead of on the stack. However, when I first saw C++ all class pointers were declared without the new keyword. When I do this and compile with g++ with the -Wall option it gives the following warning:

    Code:
    warning: ‘myClass’ is used uninitialized in this function
    Sorry if this is obvious; I've searched around a lot for the advantages and disadvantages and the only thing I can find is the bit about the stack vs. the heap, and that you need to delete any object created on the heap. Is using the stack somehow faster in terms of performance? If both ways are acceptable, why does g++ generate a warning?

    Thanks!

  2. #2
    Join Date
    Jul 2008
    Posts
    32

    Re: Declare class pointer with or without new

    Sorry, I figured out the problem; the pointer is indeed uninitialized so any attempts to get anything from it leads to a seg fault. So never mind.

  3. #3
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Declare class pointer with or without new

    There are plenty of reasons why you'd declare a pointer without using new. In fact, in a proper C++ program the usage of new should be minimized, and when you do call it the result should almost always be stored in a smart pointer, not a bare pointer.

    The usage of "new" and the usage of pointer variables sometimes go together, but you should absolutely not think of them as intrinsically linked. A pointer is just a pointer; it can point to anything, not just heap-allocated objects. A call to new just heap-allocates an object; where you choose to store the reference to it is up to you. Typically this will be in a pointer of some kind, but perhaps it's intrinsic to a pre-existing struct or class rather than declared at the point of construction, for instance.

  4. #4
    Join Date
    May 2009
    Posts
    2,413

    Re: Declare class pointer with or without new

    Quote Originally Posted by Lindley View Post
    In fact, in a proper C++ program the usage of new should be minimized,
    Where did you get this strange idea?

  5. #5
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Declare class pointer with or without new

    Quote Originally Posted by nuzzle View Post
    Where did you get this strange idea?
    http://www.research.att.com/~bs/bs_f...ml#delete-zero
    If you consider zeroing out pointers important, consider using a destroy function:

    template<class T> inline void destroy(T*& p) { delete p; p = 0; }

    Consider this yet-another reason to minimize explicit use of new and delete by relying on standard library containers, handles, etc.
    http://hissa.nist.gov/sw_develop/ir5769/node4.html
    G1.1.1 Minimizing Dynamic Memory Allocation.
    Avoid the use of C's malloc and free. Instead use (sparingly) C++'s new and delete operators.
    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; December 26th, 2009 at 06:04 PM.

  6. #6
    Join Date
    Jul 2008
    Posts
    32

    Re: Declare class pointer with or without new

    Interesting discussion in the articles linked and the post above. Thanks for providing the links.

    So is it safe to say the use of new should be minimized for multiple reasons, one major reason being that dynamically allocating memory can lead to memory leaks and allocation errors?

    I see that there are techniques to get around these issues, such as smart pointers as mentioned above and using initialization lists in a constructor, as referenced in one of the articles.

    I'm worried about basic optimization and memory management in an upcoming project that deals with large data sets. Am I correct in stating that the heap has more memory available for allocation than the stack? If so, would it be best practice to allocate large sets on the heap and pass them around by reference so as not to create needless copies of the data?

  7. #7
    Join Date
    May 2009
    Posts
    2,413

    Re: Declare class pointer with or without new

    Quote Originally Posted by MrMojoRisin View Post
    So is it safe to say the use of new should be minimized for multiple reasons, one major reason being that dynamically allocating memory can lead to memory leaks and allocation errors?
    The articles state that programmers should avoid the explicit use of new/delete. Instead alternatives such as library containers and smart pointers should be preferred. The reason is that the new/delete combination is prone to programmer mistakes and errors. So the less you use them the less you're going to f**k them up so to speak.

    But this doesn't mean dynamic memory allocations generally should be avoided in C++. Technically it's no more error prone than any other kind of memory allocation. Any memory allocation can fail. And you're not going to have any memory leaks unless you put them there yourself.

    There are situations when dynamic memory allocations shouldn't be used but the reason isn't that programmers may shoot themselves in the foot. The reason is that there are no timing guarantees. You don't know how long a heap allocation/deallocation may take so it cannot be used when you write programs with hard timing constraints.

    The object oriented programming style relies heavily on dynamic object allocations. To claim that you should avoid using new is a big joke really. It's the same as saying that C++ cannot handle OO and you better use Java or C# instead.

    So by all means, minimize the use of new/delete as much as possible because you're only human and bound to make an error sooner or later. Instead use alternatives such as library containers and smart pointers (or even a garbage collector). But it's a mistake to avoid dynamic memory allocations especially in OO. Dynamic memory allocation is an important part of the C++ language and shouldn't be avoided.
    Last edited by nuzzle; December 27th, 2009 at 03:41 AM.

  8. #8
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: Declare class pointer with or without new

    Quote Originally Posted by MrMojoRisin View Post
    I'm worried about basic optimization and memory management in an upcoming project that deals with large data sets. Am I correct in stating that the heap has more memory available for allocation than the stack?
    Yes, way more.
    If so, would it be best practice to allocate large sets on the heap and pass them around by reference so as not to create needless copies of the data?
    Yes, instead of passing variables by value, you can pass them as const-reference such that you don't have the overhead of creating a copy, but the semantics are the same.
    However, allocating large sets of data on the heap doesn't mean that you have to use new. For example, if you have a dataset of one million doubles, you could use a std::vector<double> to store the values (or whatever data structure suits your needs). The vector will internally use heap allocation to store its data. You don't have to worry about managing memory, because the vector does it for you.
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

  9. #9
    Join Date
    Jan 2008
    Location
    California, USA
    Posts
    822

    Re: Declare class pointer with or without new

    Quote Originally Posted by nuzzle View Post
    The articles state that programmers should avoid the explicit use of new/delete. Instead alternatives such as library containers and smart pointers should be preferred. The reason is that the new/delete combination is prone to programmer mistakes and errors. So the less you use them the less you're going to f**k them up so to speak.

    But this doesn't mean dynamic memory allocations generally should be avoided in C++. Technically it's no more error prone than any other kind of memory allocation. Any memory allocation can fail. And you're not going to have any memory leaks unless you put them there yourself.

    There are situations when dynamic memory allocations shouldn't be used but the reason isn't that programmers may shoot themselves in the foot. The reason is that there are no timing guarantees. You don't know how long a heap allocation/deallocation may take so it cannot be used when you write programs with hard timing constraints.

    The object oriented programming style relies heavily on dynamic object allocations. To claim that you should avoid using new is a big joke really. It's the same as saying that C++ cannot handle OO and you better use Java or C# instead.

    So by all means, minimize the use of new/delete as much as possible because you're only human and bound to make an error sooner or later. Instead use alternatives such as library containers and smart pointers (or even a garbage collector). But it's a mistake to avoid dynamic memory allocations especially in OO. Dynamic memory allocation is an important part of the C++ language and shouldn't be avoided.
    I think you're just repeating Lindley's point.
    The only difference I see is that
    Lindley strictly tries to adheres to the technicalities,
    but you're talking a lot of personal opinions, thus, more biased than Lindley's post.
    It's much better to guide the new learners to the unbiased facts,
    wouldn't you agree?

  10. #10
    Join Date
    May 2009
    Posts
    2,413

    Re: Declare class pointer with or without new

    Quote Originally Posted by potatoCode View Post
    I think you're just repeating Lindley's point.
    The only difference I see is that
    Lindley strictly tries to adheres to the technicalities,
    but you're talking a lot of personal opinions, thus, more biased than Lindley's post.
    It's much better to guide the new learners to the unbiased facts,
    wouldn't you agree?
    Neither Lindley nor Paul McKenzie are posting facts. They're posting views as much as I do. I just have a different writing style. The C++ language standard is fact, the rest is opinion.

    My point is that it's not the use of dynamic memory that should be minimized, it's the explicit use of new/delete that should be avoided because this keyword pair is especially prone to programming errors. This is an important distinction I think. So use dynamic memory to your hearts desire but seek alternatives to using new/delete directly. If that's how you read the posts of Lindley and Paul McKenzie then fine because that's how they should be read.
    Last edited by nuzzle; December 28th, 2009 at 04:53 AM.

  11. #11
    Join Date
    Jun 2008
    Posts
    592

    Re: Declare class pointer with or without new

    of course minimizing memory leaks is very important, but if you can't keep your programming from leaking memory, c++ isn't right for you. the new operator in c++ plays a very important role in its design. polymorhpic classes wouldn't even be the same without new.

    Here is some stupid code
    Code:
    char* Str = "Wow";
    delete [] Str;
    isn't that just great? or
    Code:
    char* Str = new char[100];
    free( Str );
    or
    Code:
    char* Str = (char*) malloc( sizeof( char ) * 100 );
    delete [] Str;
    or
    Code:
    shared_ptr<char> Str ( new char[100] );
    or
    Code:
    template<class T> inline void destroy(T*& p) { delete p; p = 0; }
    char* Me = new char[100];
    destroy( Me );
    or
    Code:
    void m( char* p )
    {
        delete [] p;
        p = new[100];
    }
    All those examples will be undefined behaviour I seen worser code than memory leaks . How about memory corruption?

    Code:
    int t[100];
    t[100] = 0;
    Code:
    int *t;
    *t = 100;
    Code:
    char Str[] = {'H', 'e', 'l', 'l', 'o' };
    cout << Str << endl;
    c++ is not a safe language, so it use wisely. the list can go on for miles
    Last edited by Joeman; December 28th, 2009 at 08:25 AM.
    0100 0111 0110 1111 0110 0100 0010 0000 0110 1001 0111 0011 0010 0000 0110 0110 0110 1111 0111 0010
    0110 0101 0111 0110 0110 0101 0111 0010 0010 0001 0010 0001 0000 0000 0000 0000
    0000 0000 0000 0000

  12. #12
    Join Date
    Aug 2007
    Posts
    858

    Re: Declare class pointer with or without new

    of course minimizing memory leaks is very important, but if you can't keep your programming from leaking memory, c++ isn't right for you.
    That might be a nice sentiment if it had much basis in reality. Alas, it really doesn't - there have been (and still are) innumerable programs written by experts and professionals that leak memory.

    Even C++ for all of its complexities and flaws gives you tools to make memory management less of a problem. Not taking advantage of them when you have the opportunity is simply foolish.

    polymorhpic classes wouldn't even be the same without new.
    Polymorphism works just fine without new. About the only time that new is actually required for it is when you need a container of polymorphic objects.

  13. #13
    Join Date
    Jun 2008
    Posts
    592

    Re: Declare class pointer with or without new

    Quote Originally Posted by Speedo
    That might be a nice sentiment if it had much basis in reality. Alas, it really doesn't - there have been (and still are) innumerable programs written by experts and professionals that leak memory.

    Even C++ for all of its complexities and flaws gives you tools to make memory management less of a problem. Not taking advantage of them when you have the opportunity is simply foolish.
    It has alot to do with reality. First off I know professionals make mistakes, but really not on such a basic level. I never said using stl containers is bad and should be avoided. I bet you won't find a professional that wouldn't know how to probably handle memory.

    Quote Originally Posted by Speedo
    Polymorphism works just fine without new. About the only time that new is actually required for it is when you need a container of polymorphic objects.
    and I think polymorphic objects in a container is important and there more reasons new is required than for placing derived objects into a container. Consider a factory design pattern. Alot depends on what is occuring at runtime and loads the specific derived type based on requirements. It would be hard to replace new with a local scoped object. It is possible, but wouldn't look as clean.
    0100 0111 0110 1111 0110 0100 0010 0000 0110 1001 0111 0011 0010 0000 0110 0110 0110 1111 0111 0010
    0110 0101 0111 0110 0110 0101 0111 0010 0010 0001 0010 0001 0000 0000 0000 0000
    0000 0000 0000 0000

  14. #14
    Join Date
    Feb 2005
    Location
    "The Capital"
    Posts
    5,306

    Re: Declare class pointer with or without new

    Quote Originally Posted by nuzzle View Post
    The articles state that programmers should avoid the explicit use of new/delete. Instead alternatives such as library containers and smart pointers should be preferred. The reason is that the new/delete combination is prone to programmer mistakes and errors. So the less you use them the less you're going to f**k them up so to speak.

    But this doesn't mean dynamic memory allocations generally should be avoided in C++. Technically it's no more error prone than any other kind of memory allocation. Any memory allocation can fail. And you're not going to have any memory leaks unless you put them there yourself.

    There are situations when dynamic memory allocations shouldn't be used but the reason isn't that programmers may shoot themselves in the foot. The reason is that there are no timing guarantees. You don't know how long a heap allocation/deallocation may take so it cannot be used when you write programs with hard timing constraints.

    The object oriented programming style relies heavily on dynamic object allocations. To claim that you should avoid using new is a big joke really. It's the same as saying that C++ cannot handle OO and you better use Java or C# instead.

    So by all means, minimize the use of new/delete as much as possible because you're only human and bound to make an error sooner or later. Instead use alternatives such as library containers and smart pointers (or even a garbage collector). But it's a mistake to avoid dynamic memory allocations especially in OO. Dynamic memory allocation is an important part of the C++ language and shouldn't be avoided.
    I think you took the points posted by Lindley and Paul to a wrong context/interpretation and posted the above. I don't see where they said to avoid dynamic memory. Of course, its essential. But the point I understand that was being made, was about handling the memory yourself using plain malloc/free, new/delete or whatever allocation/deallocation routines which can be beneficial to beginners (this is an opinion). I don't think they questioned the dynamic memory as such just the way they are handled in a program. These are so called guidelines, if you feel comfortable with fire, of course you are free to tame it.
    Quote Originally Posted by nuzzle View Post
    So by all means, minimize the use of new/delete as much as possible because you're only human and bound to make an error sooner or later. Instead use alternatives such as library containers and smart pointers (or even a garbage collector). But it's a mistake to avoid dynamic memory allocations especially in OO. Dynamic memory allocation is an important part of the C++ language and shouldn't be avoided.
    I don't see a disagreement here, so all's well.

  15. #15
    Join Date
    Aug 2007
    Posts
    858

    Re: Declare class pointer with or without new

    It has alot to do with reality. First off I know professionals make mistakes, but really not on such a basic level. I never said using stl containers is bad and should be avoided. I bet you won't find a professional that wouldn't know how to probably handle memory.
    That's exactly the point. Knowing how to properly handle memory is trivial. If you know "delete everything you new", then congratulations, technically you know how to handle memory.

    In reality, however, it is often not so trivial to implement that simple phrase. For example, making sure that your classes can properly handle dynamic memory during copy or assignment. Making sure that code is exception-safe. Etc, etc. The blunt truth is that a whole lot of C++ programmers, whatever they know about memory management, don't pay a bit of attention to those little details until they run into a problem caused by them.

    And that's why so many people preach:
    Don't use new unless you have to.
    When you have to, take advantage of things like smart pointers.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured