Checking for dynamically allocated memory in copy constructors

This is a discussion on Checking for dynamically allocated memory in copy constructors within the C++ Programming forums, part of the General Programming Boards category; I'm trying to write a copy constructor that needs to throw the memory Allocation error exception if no dynamic memory ...

  1. #1
    Registered User
    Join Date
    Aug 2004
    Posts
    12

    Checking for dynamically allocated memory in copy constructors

    I'm trying to write a copy constructor that needs to throw the memory Allocation error exception if no dynamic memory is available. I have only overloaded the = operator but do not want to overload the == operator. I am receiving errors and would appreciate any help. Thanks.

    Code:
    dynamicInt::dynamicInt(const dynamicInt& obj)
    {
    	if(obj==NULL)
    	{
    		cerr<<"Memory allocation error";
    		exit(1);
    	}
    	*ptr = obj.getData();
    }
    The error I get is: error C2676: binary '==' : 'const class dynamicInt' does not define this operator or a conversion to a type acceptable to the predefined operator

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    A reference can never be null, so why are you checking it for null?

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Aug 2004
    Posts
    12
    How would I check to see if there is dynamic memory available to create a new object within the copy constructor?

  4. #4
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,669
    call new

    gg

  5. #5
    Registered User
    Join Date
    Sep 2004
    Posts
    719
    let me give you a clue...i can give you the solution to your error, but it will help you understand C/C++ alot more if you figure out my way.....

    pointers do not store any of the data that they POINT to, they are just 2 memory addresses, the address of the pointer itself, and the address of the data they point to....

    references are aliases (basically just another name for a variable)...for now just think of them as any other variable except that it can change (or reads) variables in a different scope.

  6. #6
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,088
    You don't have to throw an exception if there is not enough memory to create your object, because the code that creates the object will basically do it for you. For example, if the user uses new to create your object, then new will throw a bad_alloc exception if there is not enough memory. If the user of your class creates the object on the stack, then it isn't dynamic memory anymore. If, inside your copy constructor (or your real constructor for that matter) you allocate dynamic memory using new, and new fails because you are out of memory, then a bad_alloc exception will be thrown. If you ignore it, the exception will automatically propagate outside of your constructor, so it effectively is like you threw the exception without you having to do any work.

    Of course, in your code above, you do not do any dynamic memory allocation, so there is no need for you to worry about throwing an exception if there isn't enough memory. If you plan on adding dynamic memory allocation to that constructor, and you are using an old compiler that doesn't throw an exception when it runs out of memory, then you can still throw an exception yourself by checking the pointer for null after you use new.

  7. #7
    Registered User
    Join Date
    Aug 2004
    Posts
    12
    Does this seem correct?

    Code:
    dynamicInt::dynamicInt(const dynamicInt& obj)
    {
    
    	ptr = new int;
    	if(ptr ==NULL)
    	{cout<<"error"<<endl;}
    	*ptr = obj.getData();
    }

  8. #8
    Registered User Kybo_Ren's Avatar
    Join Date
    Sep 2004
    Posts
    136
    Code:
    dynamicInt::dynamicInt(const dynamicInt& obj)
    {
    
            int *ptr;
    
            try{
    	        ptr = new int;
            }
    
            catch(std::bad_alloc)
            {
                    //memory allocation failed
            }
    	
    	*ptr = obj.getData();
    }
    Or if you with it to propogate outside of the constructor:
    Code:
    dynamicInt::dynamicInt(const dynamicInt& obj)
    {
    
            int *ptr;
            ptr = new int;	
    	*ptr = obj.getData();
    }
    But make sure you use delete in the destructor.

  9. #9
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,088
    Yes, hkmixxa, that is closer. If you want to throw an exception, you still have to throw an exception. As I mentioned earlier, and as Kybo_Ren's examples show, new should already throw an exception if it fails, so his second example would be completely fine. If new failed, it would immediately stop in the middle of the function and the exception would be thrown.

    However, some compilers don't work correctly when new fails. They return 0 (or NULL) instead of throwing an exception. If you aren't sure which one your compiler does, you can code like this:
    Code:
    dynamicInt::dynamicInt(const dynamicInt& obj)
    {
    	ptr = new int;
    	if(ptr == 0)
    		throw std::bad_alloc();
    
    	*ptr = obj.getData();
    }
    You can also test which way your compiler reports the error with this code:
    Code:
    #include <iostream>
    #include <limits>
    
    int main()
    {
        try
        {
            double* p = new double[std::numeric_limits<int>::max()];
            if (p != 0)
            {
                std::cout << "Memory allocation succeeded.  Increase allocation size!" << std::endl;
                return EXIT_FAILURE;
            }
            std::cout << "2. Returned null pointer on failure." << std::endl;
        }
        catch(const std::bad_alloc& )
        {
            std::cout << "1. Threw bad_alloc exception on failure." << std::endl;
        }
        catch(...)
        {
            std::cout << "Some other exception was thrown!" << std::endl;
        }
        return EXIT_SUCCESS;
    }
    If it outputs 1, then you can use Kybo_Ren's second example and allow new to throw the exception for you. If it outputs 2, then you must check the return of new for against 0 (or NULL).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Mutex and Shared Memory Segment Questions.
    By MadDog in forum Linux Programming
    Replies: 14
    Last Post: 06-20-2010, 04:04 AM
  2. Checking for memory leaks
    By Bladactania in forum C Programming
    Replies: 5
    Last Post: 02-10-2009, 11:58 AM
  3. Malloc & Calloc difference in terms of memory allocated
    By swapnaoe in forum C Programming
    Replies: 2
    Last Post: 04-19-2007, 12:57 AM
  4. Any Memory Leak Checking Tool?
    By George2 in forum C Programming
    Replies: 4
    Last Post: 06-21-2006, 11:02 PM
  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

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