copy constructor issues

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • momotaro
    Contributor
    • Sep 2006
    • 357

    copy constructor issues

    is this code correct ?
    Code:
    DynamicVector::DynamicVector(const DynamicVector& copy)
    {
    	if(this != &copy)
    	{
    		this->length = copy.length;
    		for(int i = 0; i < copy.length; i++)
    			*(this->v+i) = *(copy.v+i);
    	}
    }
    because when I do things like that:
    Code:
    DynamicVector v(5), t(7);
    v=t;
    it works with or without the copy constructor !!!
    and upon closing my console gives me that error in both cases:
    Debug Assertion Failed!
    Program:...o
    ...\MyProgram.e xe
    File:...\dbgdel .cpp
    Line:52
    Expression:_BLO CK_TYPE_IS_VALI D(pHead->nBlockUse)
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Well you always have a copy constructor, if you don't write one the compiler generates a default on that does a plain copy of the variables. The problem with this is if you have data allocated to a pointer, both instances of the class end up pointing at the same piece of allocated data and which every gets destroyed first deletes that data leaving the other instance with an invalid pointer.

    In your code you copy to this->v but a see no attempt to ensure that it points to a block of data that is long enough. If this->length != copy.length then you should be doing something about deleting the current this->v and allocating new data for it.

    Comment

    • hype261
      New Member
      • Apr 2010
      • 207

      #3
      Code:
      DynamicVector v(5), t(7); 
      v=t;
      This code right here will call the assignment operator not the copy constructor.

      To call the copy constructor use...

      Code:
      DynamicVector t(7);
      DynamicVector v = t;

      Comment

      Working...