Thread: Question regarding Memory Leak

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    Actually, the assignment operator is needed for both purposes. It's certainly true the destructor prevents some memory leaks, but the assignment operator prevents others, in addition to doing a deep copy.

    For example, assume you do this (where MyClass is a poorly-written class that has no assignment operator, and some pointer variable ptr):

    MyClass a, b;
    a = b;

    The assignment does two things:
    1. It does a shallow copy of b.ptr to a.ptr, making both pointers point to the same data, leading to the issue you described,
    2. Causes a memory leak. Can you see how? Hint: What about the memory that used to be pointed at by a.ptr?
    Last edited by Cat; 12-05-2007 at 08:40 PM.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Assignment Operator, Memory and Scope
    By SevenThunders in forum C++ Programming
    Replies: 47
    Last Post: 03-31-2008, 06:22 AM
  2. Memory Leak Help
    By (TNT) in forum Windows Programming
    Replies: 3
    Last Post: 06-19-2006, 11:22 AM
  3. Memory Leak
    By Berticus in forum C++ Programming
    Replies: 5
    Last Post: 07-20-2005, 05:11 PM
  4. Memory Address of Array Question
    By Zeusbwr in forum C++ Programming
    Replies: 3
    Last Post: 10-24-2004, 09:58 AM
  5. Is it necessary to write a specific memory manager ?
    By Morglum in forum Game Programming
    Replies: 18
    Last Post: 07-01-2002, 01:41 PM