CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 10 of 10

Thread: C++ and orphans

  1. #1
    Join Date
    Jan 2009
    Posts
    1,689

    C++ and orphans

    I'm still getting back into the swing of C++ and I have a question. If I create an orphan, what happens to it?

    Code:
    class newclass;
    newclass = class();
    Memory leak, or does C++ have a garbage collector that will take care of that automatically?

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

    Re: C++ and orphans

    C++ does not have a garbage collector. However, the above code will not cause a memory leak either. Memory leaks are *only* possible when doing dynamic allocation, which is not done there. That means you need to match up:

    new -> delete
    new[] -> delete[]
    malloc() -> free() or realloc(0)
    calloc() -> free() or realloc(0)
    realloc(nonzero) -> free() or realloc(0)

    If you have any of those five types of allocation without a *matching* deallocation call, you've got a memory leak. Other than that, you're fine.

  3. #3
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: C++ and orphans

    Not sure what that code does, but there is no garbage collection in C++. Memory allocated on the stack is freed when it goes out of scope. Memory on the heap (using new) remains until you call delete.

  4. #4
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: C++ and orphans

    You might want to give an example that could actually compile.

    Quote Originally Posted by ninja9578
    Memory leak, or does C++ have a garbage collector that will take care of that automatically?
    Between the two the answer is probably "memory leak", since C++ does not have a garbage collector unless you plug in one yourself.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  5. #5
    Join Date
    Jan 2009
    Posts
    1,689

    Re: C++ and orphans

    using namespace std;
    #include <string>
    #include <vector>

    class semidynamic{
    semidynamic(void){
    temp = new vector<int>;
    }
    ~semidynamic(void){
    delete temp;
    }
    vector<int> * temp;
    }


    int main(){
    //All on the heap
    semidynamic one;
    semidynamic two;
    one = two;
    }

    At the end of main, the reference to one is lost, even though the object itself was on the stack, it allocated something dynamically. Will this cause a leak? ie, will C++ simply remove 'one' when it goes out of scope, or will it call the destructor?

  6. #6
    Join Date
    Jun 2008
    Posts
    37

    Re: C++ and orphans

    The destructor IS called! and the previous resources MUST be reclaimed!

  7. #7
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    Re: C++ and orphans

    Quote Originally Posted by ninja9578 View Post
    Code:
    using namespace std;
    #include <string>
    #include <vector>
    
    class semidynamic{
         semidynamic(void){
              temp = new vector<int>;
         }
         ~semidynamic(void){
             delete temp;
         }
         vector<int> * temp;
    }
    
    
    int main(){
         //All on the heap
         semidynamic one;
         semidynamic two;
         one = two;      // MEMORY LEAK !!
    }
    At the end of main, the reference to one is lost, even though the object itself was on the stack, it allocated something dynamically. Will this cause a leak? ie, will C++ simply remove 'one' when it goes out of scope, or will it call the destructor?
    Please use code tags !

    Your application leaks memory on the line specified, because your class does not implement operator=. Thus when assigning two to one, the memory previously allocated to one is lost.
    More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf

    Premature optimization is the root of all evil --Donald E. Knuth


    Please read Information on posting before posting, especially the info on using [code] tags.

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

    Re: C++ and orphans

    There is very little reason to dynamically allocate a std::vector, since a std::vector is by nature a dynamic-sized object.

    However, for the purposes of that dummy example: Yes, as has been said, you leak the memory allocated by "one". But it's worse than that-----*both* the destructors of one and two will now try to release the same memory, leading to a "double delete" situation, which can crash the program.

    There are two rules to keep in mind when designing a class:
    1) Don't use pointer members unless you absolutely have to. Whenever possible, substitute an STL container or other objects will well-defined copy semantics. Pointers which just maintain a reference to something that the class didn't allocate are fine.
    2) If your class *does* have any heap-allocated members, you need to define (a) the destructor, (b) the copy constructor, and (c) operator=.
    Last edited by Lindley; February 4th, 2009 at 09:16 AM.

  9. #9
    Join Date
    Nov 2003
    Posts
    1,405

    Re: C++ and orphans

    Quote Originally Posted by ninja9578 View Post
    Will this cause a leak? ie, will C++ simply remove 'one' when it goes out of scope, or will it call the destructor?
    Your main option of course is to learn how to deal with the "big three".

    http://en.wikipedia.org/wiki/Rule_of...B_programming)

    Or, if you're an escapist like me, you dodge the whole issue by only using these kinds of types in your classes,

    - any primitive,
    - any STL container (including array), and
    - any heap allocated object as long as you put it in a shared_ptr (a smart pointer).

    Both array and shared_ptr will be part of the upcoming C++ standard but are already available in the std:tr1 namespace in many compilers. If not you'll find them in Boost.

    This is a leak-free version of your example. Totallydynamic replaces the vector you had so it becomes possible to trace the dynamic construction/destruction on the heap.

    Code:
    class totallydynamic {
    public:
       totallydynamic(int i) : n(i){
          std::cout << "totallydynamic constructed: " << n << "\n";
       }
       ~totallydynamic(){
          std::cout << "totallydynamic destructed: " << n << "\n";
       }
    private:
       int n;
    };
    //
    class semidynamic {
    public:
       semidynamic(int i) : n(i), temp(new totallydynamic(i)) {
          std::cout << "semidynamic constructed: " << n << "\n";
       }
       ~semidynamic(){
          std::cout << "semidynamic destructed: " << n << "\n";
       }
    private:
       int n;
       std::tr1::shared_ptr<totallydynamic> temp; // heap allocated object held in smart pointer
    };
    //
    void test(){
       semidynamic one(1); // constructed on the stack
       semidynamic two(2); // constructed on the stack.
       std::cout << "before assignment\n";
       one = two;      // copy assignment, no memory leak
       std::cout << "after\n";
    } // objects in one and two get destructed
    If you run it you will note that all objects get destructed properly, including the heap allocated ones. But semidynamic(1) never gets destructed, why? Well its destructor wasn't called but all data got properly destructed, including totallydynamic(1). And at the end of main semidynamic(2) get's destructed twice, why? It's because after the assignment both one and two holds a copy of this object. Still, thanks to the shared_ptr, totallydynamic(2) gets destructed once only.

    Finally note that the above assignment is shallow. This means that the temp pointer gets copied, not the totallydynamic object it's pointing to. The shared_ptr's job is to make sure the heap allocated object it points gets destructed, and destructed once only.
    Last edited by _uj; February 5th, 2009 at 05:12 AM.

  10. #10
    Join Date
    Jun 2008
    Posts
    37

    Re: C++ and orphans

    I envy with your skills *uj*,
    about dynamic allocation : iam worse
    about multiple talks of programming theories: im worse
    ... all worse than you
    []about material search: iam best since i have a upper BIG CD collection up the shelf that i can have it scan for me to read, copy and paste.

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