문제

I found this piece of code in the following link

http://www.tutorialspoint.com/cplusplus/cpp_copy_constructor.htm

Line::Line(const Line &obj)
{
cout << "Copy constructor allocating ptr." << endl;
ptr = new int;
*ptr = *obj.ptr; // copy the value
}

where Line is defined as:

class Line
{
public:
  int getLength( void );
  Line( int len );             // simple constructor
  Line( const Line &obj);  // copy constructor
  ~Line();                     // destructor

private:
  int *ptr;
 };

So help me understand.. What is the point in allocating memory for *ptr inside the Copy constructor ? By assigning it to *obj.ptr, essentially they are both pointing to the same locations in memory? Why should I use the new here, if it is only going to perform a shallow copy, that is copy the pointer address of the intended variable ?

도움이 되었습니까?

해결책

This is the way for making deep copies. The pointers don't point to the same location, since you dynamically alocated ptr (so it has a it's own new location). After that your copying just the value of the pointer, by dereferencing them.

다른 팁

Each Line instance has its own dynamically allocated int. The copy constructor is allocating a new int and then copying the value of the int being pointed at, it is not copying the pointer itself.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top