Thread: Copy assignment help.

  1. #1
    Registered User
    Join Date
    Feb 2009

    Copy assignment help.


    I'm not sure if the book is incorrect or I simply cannot understand this code yet:

    class vector {
    	int sz;
    	double* elem; // pointer to the elements
    	void copy(const vector& arg);
    	vector& operator=(const vector&);
    void vector::copy(const vector& arg)
    	for (int i = 0; i<; ++i) elem[i] = arg.elem[i];
    vector& vector::operator =(const vector& a)
    	double* p = new double[];  // allocate new space
    	copy(a);  // copy elements
    	delete[] elem;  //deallocate old space
    	elem = p;  // reset elem;
    	return *this;
    The part I don't understand is the operator overload function. The new space has been allocated and then elements copied, but where are these elements copied to? According to the copy function, they are copied to elem[i] of the vector being copied to. However, in the = overload, that elem is deleted immediately after the copy function is called and then reset with p. Are the elements copied into p, if so how?


  2. #2
    The larch
    Join Date
    May 2006
    Yes, it appears the example is broken.

    Rewrite the copy function so it lets you choose, where to copy to or just replace the custom copy with std::copy (#include <algorithm>):

    std::copy(a.elem, a.elem +, p);
    (Note, copy to the new buffer that was created!)
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    Registered User
    Join Date
    Feb 2009
    Thanks, I did think it was wrong. It's so frustrating when that happens and you are trying to learn from incorrect material.

    I will look into it further from your suggestions.


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. default implementation of assignment operator
    By George2 in forum C++ Programming
    Replies: 3
    Last Post: 12-15-2007, 12:49 AM
  2. Doing maths to copy constructed variables
    By Paul Skinner in forum C++ Programming
    Replies: 7
    Last Post: 12-11-2007, 05:31 PM
  3. Copy constructor for Queue ADT (as an Array)
    By clegs in forum C++ Programming
    Replies: 2
    Last Post: 11-28-2007, 11:05 PM
  4. containers/ assignment operator
    By Kirdra in forum C++ Programming
    Replies: 2
    Last Post: 10-08-2004, 10:17 AM
  5. copy constructor
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 09-26-2001, 05:17 PM