CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 2 of 2 FirstFirst 12
Results 16 to 25 of 25
  1. #16
    Join Date
    Jun 2012
    Posts
    127

    Re: Try to put own Class to creating by me <Template> like vector. unknow compile err

    Quote Originally Posted by oteel View Post
    Probable it'll be post in style of captain obvious but if I commented out the code related this try-catch blocks in array.cpp and main.cpp then everything work fine... Finally...


    ups... sorry... silly mistake I handled it
    excess try in body of SetElement()
    IT's working !!!!!!IT's working !!!!!!IT's working !!!!!!IT's working !!!!!!IT's working !!!!!!IT's working !!!!!!IT's working !!!!!!IT's working !!!!!!IT's working !!!!!!IT's working !!!!!!IT's working !!!!!!

  2. #17
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Try to put own Class to creating by me <Template> like vector. unknow compile err

    Quote Originally Posted by oteel View Post
    IT's working !!!!!!IT's working !!!!!!IT's working !!!!!!IT's working !!!!!!IT's working !!!!!!IT's working !!!!!!IT's working !!!!!!IT's working !!!!!!IT's working !!!!!!IT's working !!!!!!IT's working !!!!!!
    See that? Take your time, listen to what is being taught, and you can get the work done.

    OK. If you want to post the final solution, you should do that. Maybe there are other issues that are still there.

    Regards,

    Paul McKenzie

  3. #18
    Join Date
    Jun 2012
    Posts
    127

    Re: Try to put own Class to creating by me <Template> like vector. unknow compile err

    Quote Originally Posted by Paul McKenzie View Post
    See that? Take your time, listen to what is being taught, and you can get the work done.

    OK. If you want to post the final solution, you should do that. Maybe there are other issues that are still there.

    Regards,

    Paul McKenzie
    Yep, many thanks in advance!!! it will be great , hears your comments !!!
    I really want to grow. It's ok that this will happen very slowly, step by step, the error after error, inch by inch, through the sweat and bloody tears. I think this is what separate the professional from the amateur. First at all hard working. I want to become a professional in one day.


    Code:
    //array.h
    #ifndef Array_H
    #define Array_H
    
    template <class Type> //Remove the "=double" default parameter.
    class Array
    {
    private:
      int m_size;
      Type* m_data; //m_data should be a pointer, since you want to allocate data to it
    
    public:
      Array();
      Array(int new_size);
      Array(const Array<Type>& ar);
      ~Array(); //Don't make your destructor virtual. There is no reason to do it.
      const Type& Array<Type>::GetElement(int index) const;
    void Array<Type>::SetElement(const Type& type_object, int index);
      Array<Type>& operator=(const Array& ar); //Const correctness here.
    
      void Swap(Array& ar);  
    };
    
    //Implementation goes here
    
    #endif
    
    //point.h
    
    #include "array.h"
    #include <sstream>
    #include <iostream>
    using namespace std;
    
    
    class Point
    {
    private:
        double m_x;                                
        double m_y;                                
    public:
        // Constructors
        Point(): m_x(0), m_y(0) {};                            
    	Point(double new_x, double new_y) : m_x(new_x), m_y(new_y) {};
    	friend ostream& operator << (ostream& os, const Point& point)
    {
        return os << point.ToString();
    }
    	std::string Point::ToString(void) const                // create a string representation of a point
    {
    // create a string like: “Point(1.5, 3.9)”
          std::ostringstream os;
        os << m_x << " , " << m_y;
        std::string double_string = os.str();
     
        return "Point(" + double_string + ")";
    }
    };
    
    //array.cpp
    #include "Array.h"
    #include <sstream>
    #include <iostream>
    #include <exception>
    using namespace std;
    #ifndef Array_CPP
    #define Array_CPP
    
    
    template <class Type>
    Array<Type>::Array() : m_size(0), m_data(0)
    { }
    
    template <class Type>
    Array<Type>::Array(int new_size) : m_size(new_size), m_data(new Type[new_size])
    { }
    
    template <class Type>
    Array<Type>::~Array()
    {
      //Technically, the if is not necessary
      if(m_data)
      {
        delete[] m_data;
        m_data = 0;
      }
    
      //Not necessary either, but just to be clean
      m_size = 0;
    }
    
    template <class Type>
    Array<Type>::Array(const Array& ar) : m_data(0), m_size(0)
    {
      if(!ar.m_data) {return;}
    
      Array tmp; //Copy construct into another temporary array, this way, if something throws, tmp will clean itself up.
    
      //Create the array
      tmp.m_data = new Type[ar.m_size];
      tmp.m_size = ar.m_size;
    
      //Copy the array elements
      for(int i = 0; i < tmp.m_size; ++i)
        {tmp.m_data[i] = ar.m_data[i];}
    
      //All done! swap into this!
      this->Swap(tmp);
    }
    
    template <class Type>
    Array<Type>& Array<Type>::operator=(const Array& ar)
    {
      //Check self assign:
      if(this == &ar) {return *this;}
    
      Array<Type> copy(ar); //Create a copy of ar; If this fails, then *this will not be changed, and nothing will leak
    
      //Succeeded creating copy. Now we can put it inside this
      this->Swap(copy); //And then swap the copy into this!
    
      return *this;
    }
    
    template <class Type>
    void Array<Type>::Swap(Array& ar)
    {
      Type* data = m_data;
      int   size = m_size;
      m_data = ar.m_data;
      m_size = ar.m_size;
      ar.m_data = data;
      ar.m_size = size;
    }
    
    template <class Type> 
    void Array<Type>::SetElement(const Type& type_object, int index)
    {
    //	try
    //	{
    		if (index >= m_size || index < 0 )
    		{ throw std:: out_of_range ("out of range error in void Array<Type>::SetElement");}
    		m_data[index] = type_object;
    		cout << "Set Element " << type_object  << endl;
    //	}
    	
    }
    template <class Type> 
    const Type& Array<Type>::GetElement(int index) const
    {
    	
    		if (index > m_size || index < 0)
    		{ throw std::out_of_range ("Out of range error in void Array<Type>::GetElement");} 
    
    	return m_data[index];
    }
    
    #endif //Array_CPP
    
    		//main.cpp
    		#include "point.h"
    		#include <iostream>
    		#include <sstream>
    		#include "array.cpp"
    		#include <exception>
    		using namespace std;
    
    int main()
    {
    		try
    		{
    			Point *p1 = new Point (1,12);
    				cout << endl;
    			Array<Point> arr1(5);
    			arr1.SetElement(*p1,1);
    				cout << endl;
    			arr1.GetElement(1) ;
    			delete p1;
    			return 0;
    		}
    		catch(const std::exception& e)
    		{
    			std::cout << e.what() << std::endl;
    			throw;
    		}
    	//	system ("pause");
    }
    Last edited by oteel; June 18th, 2012 at 07:15 AM.

  4. #19
    Join Date
    Jun 2012
    Posts
    127

    Re: Try to put own Class to creating by me <Template> like vector. unknow compile err

    I take my words back everything fine about GetElement() function
    Sorry
    Last edited by oteel; June 18th, 2012 at 07:36 AM.

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

    Re: Try to put own Class to creating by me <Template> like vector. unknow compile err

    Quote Originally Posted by oteel View Post
    Yep, many thanks in advance!!! it will be great , hears your comments !!!
    This code will leak memory if the Array constructor throws an exception (due to "new" in the constructor throwing an exception):
    Code:
    int main()
    {
        try
       {
    	Point *p1 = new Point (1,12);
    	cout << endl;
    	Array<Point> arr1(5);  // what if constructor throws an exception?
                                                        // Point is never cleaned up!!
    	arr1.SetElement(*p1,1);
    	cout << endl;
    	arr1.GetElement(1) ;
    	delete p1;
    	return 0;
        }
        catch(const std::exception& e)
       {
            std::cout << e.what() << std::endl;
        }
    }
    The issue is this -- in your main() function, there is no need to dynamically allocate anything. Not only isn't it necessary, it is great it doesn't have to be dynamically allocated, as the Point destructor will be called automatically when the Point variable goes out of scope.

    To "fix" your code, you would have to delete p1 inside the catch. But even that's a problem -- what if the new Point throws an exception? What do you do then? The Point was never created, so deleting something that was never created is wrong.

    This all becomes a tangled mess for no reason. The easiest fix is this:
    Code:
    int main()
    {
        try
       {
    	Point p1(1,12);
    	cout << endl;
    	Array<Point> arr1(5);  // what if constructor throws an exception?
                                                        // Point is never cleaned up!!
    	arr1.SetElement(p1,1);
    	cout << endl;
    	arr1.GetElement(1) ;
    	return 0;
        }
        catch(const std::exception& e)
       {
            std::cout << e.what() << std::endl;
        }
    }
    There is no call to "new Point", therefore no need to figure out when and where to "delete" this Point. Everything, Point and the Array, get cleaned up correctly and automatically, regardless of whether an exception is thrown or not.

    The bottom line is that you should use objects, not pointers, and only use pointers when it is necessary to use them. Objects (if written correctly) will automatically clean themselves up on destruction. Dynamically allocated memory does not clean itself up -- all of those responsibilities are on you.

    Regards,

    Paul McKenzie

  6. #21
    Join Date
    Jun 2012
    Posts
    127

    Re: Try to put own Class to creating by me <Template> like vector. unknow compile err

    Quote Originally Posted by Paul McKenzie View Post
    This code will leak memory if the Array constructor throws an exception (due to "new" in the constructor throwing an exception):
    Code:
    int main()
    {
        try
       {
    	Point *p1 = new Point (1,12);
    	cout << endl;
    	Array<Point> arr1(5);  // what if constructor throws an exception?
                                                        // Point is never cleaned up!!
    	arr1.SetElement(*p1,1);
    	cout << endl;
    	arr1.GetElement(1) ;
    	delete p1;
    	return 0;
        }
        catch(const std::exception& e)
       {
            std::cout << e.what() << std::endl;
        }
    }
    The issue is this -- in your main() function, there is no need to dynamically allocate anything. Not only isn't it necessary, it is great it doesn't have to be dynamically allocated, as the Point destructor will be called automatically when the Point variable goes out of scope.

    To "fix" your code, you would have to delete p1 inside the catch. But even that's a problem -- what if the new Point throws an exception? What do you do then? The Point was never created, so deleting something that was never created is wrong.

    This all becomes a tangled mess for no reason. The easiest fix is this:
    Code:
    int main()
    {
        try
       {
    	Point p1(1,12);
    	cout << endl;
    	Array<Point> arr1(5);  // what if constructor throws an exception?
                                                        // Point is never cleaned up!!
    	arr1.SetElement(p1,1);
    	cout << endl;
    	arr1.GetElement(1) ;
    	return 0;
        }
        catch(const std::exception& e)
       {
            std::cout << e.what() << std::endl;
        }
    }
    There is no call to "new Point", therefore no need to figure out when and where to "delete" this Point. Everything, Point and the Array, get cleaned up correctly and automatically, regardless of whether an exception is thrown or not.

    The bottom line is that you should use objects, not pointers, and only use pointers when it is necessary to use them. Objects (if written correctly) will automatically clean themselves up on destruction. Dynamically allocated memory does not clean itself up -- all of those responsibilities are on you.

    Regards,

    Paul McKenzie
    What if I needed allocate my object dynamically ?
    I should re-write exceptional handling part of program by myself ???

  7. #22
    Join Date
    Aug 2000
    Location
    New York, NY, USA
    Posts
    5,656

    Re: Try to put own Class to creating by me <Template> like vector. unknow compile err

    Quote Originally Posted by oteel View Post
    this is picture of mistake
    I see that your current problem is solved, but would like to point that, according to your screenshot, your latest build failed and you are debugging something else.
    Vlad - MS MVP [2007 - 2012] - www.FeinSoftware.com
    Convenience and productivity tools for Microsoft Visual Studio:
    FeinWindows - replacement windows manager for Visual Studio, and more...

  8. #23
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Try to put own Class to creating by me <Template> like vector. unknow compile err

    Quote Originally Posted by oteel View Post
    What if I needed allocate my object dynamically ?
    Then you allocate dynamically. The main() function you have certainly does not need any dynamic allocation whatsoever, so why do it (and also, cause a memory leak)?
    I should re-write exceptional handling part of program by myself ???
    Why do you need to rewrite anything in main()?

    If you look at my main() function, it is the same as your code, but it is cleaned up and doesn't leak memory. The reason why it doesn't leak memory is because I am using objects, not mismanaging dynamically allocated memory.

    The purpose of main() is to test your Array class, correct? So why are you making main() so complex with all of those calls to new and delete? It's no good if main() is supposed to be your testbed function, and even the main() has bugs. The main() should be bug free.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; June 18th, 2012 at 11:17 AM.

  9. #24
    Join Date
    Jun 2012
    Posts
    127

    Re: Try to put own Class to creating by me <Template> like vector. unknow compile err

    Quote Originally Posted by VladimirF View Post
    I see that your current problem is solved, but would like to point that, according to your screenshot, your latest build failed and you are debugging something else.
    thanks Vladimir for this comment

  10. #25
    Join Date
    Jun 2012
    Posts
    127

    Re: Try to put own Class to creating by me <Template> like vector. unknow compile err

    Quote Originally Posted by Paul McKenzie View Post
    Then you allocate dynamically. The main() function you have certainly does not need any dynamic allocation whatsoever, so why do it (and also, cause a memory leak)?
    Why do you need to rewrite anything in main()?

    If you look at my main() function, it is the same as your code, but it is cleaned up and doesn't leak memory. The reason why it doesn't leak memory is because I am using objects, not mismanaging dynamically allocated memory.

    The purpose of main() is to test your Array class, correct? So why are you making main() so complex with all of those calls to new and delete? It's no good if main() is supposed to be your testbed function, and even the main() has bugs. The main() should be bug free.

    Regards,

    Paul McKenzie
    It's sound very reasonably, without doubt, I address this question about necessary of a dynamic object to my TA.

Page 2 of 2 FirstFirst 12

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