2014-03-04 4 views
2

최근에 오버로드 된 연산자를 배우고 곧 오버로드 된 복사 연산자가 발생했습니다. 몇 가지 예제를 시도했지만 실제로 형식을 이해할 수 없었습니다. 글쎄, 내가 C++의 초보자이기 때문에 더 쉬운 용어로 코드를 설명 할 수 있다면 도움이 될 것입니다.복사 할당 연산자 오버로드

#include <iostream> 
using namespace std; 

class Point{ 
private: 
    int* lobster; 
public: 
    Point(const int somelobster){ 
     lobster = new int; 
     *lobster = somelobster; 
    } 
    //deep copy 
    Point(const Point& cpy){ //copy of somelobster(just to make sure that it does not do shallow copy) 
     lobster = new int; 
     *lobster = *cpy.lobster; 
    } 
    //assingment operator 
    Point& operator=(const Point& cpy){ //used to copy value 
     lobster = new int; //same thing as the original overloaded constructor 
     *lobster = *cpy.lobster; //making sure that it does not makes a shallow copy when assigning value 
     return *this; 
    } 

    void display_ma_lobster(){ //display nunber 
     cout << "The number you stored is: " << *lobster << endl; 
    } 
    ~Point(){ //deallocating memory 
     cout << "Deallocating memory" << endl; 
     delete lobster; 
    } 
}; 

int main(){ 
    Point pnt(125); 
    cout << "pnt: "; 
    pnt.display_ma_lobster(); 
    cout << "assigning pnt value to tnp" << endl; 
    Point tnp(225); 
    tnp = pnt; 
    tnp.display_ma_lobster(); 
    return 0; 
} 

하지만 정말 설명이 필요 주요 부분 :

//deep copy 
     Point(const Point& cpy){ //copy of somelobster(just to make sure that it does not do shallow copy) 
      lobster = new int; 
      *lobster = *cpy.lobster; 
     } 
     //assingment operator 
     Point& operator=(const Point& cpy){ //used to copy value 
      lobster = new int; //same thing as the original overloaded constructor 
      *lobster = *cpy.lobster; //making sure that it does not makes a shallow copy when assigning value 
      return *this; 
     } 

+0

할머니에게 불쾌감을주지 않는 이름으로 '쓰레기'라는 이름을 바꾸십시오. –

+3

@ Cheersandhth.-Alf http://www.amazon.com/Everyone-Turtleback-Library-Binding-Edition/dp/0613685725 – Potatoswatter

+0

@ Cheersandhth.- Alf 네, 죄송합니다. 실제로 TheNewBoston 스타일을 따르고있었습니다. – Jim

답변

2

복사 할당 연산자가 이미 소유 기존의 자원을 사용할 수 있습니다 시간 내 주셔서 감사합니다 어쨌든 여기 내 코드입니다 그 물체. 그것은 생성자와 같지 않습니다. (귀하의 복사 생성자가 정확한지 확인하십시오.)

//assingment operator 
Point& operator=(const Point& cpy){ //used to copy value 
    // Do not allocate anything here. 
    // If you were to allocate something, that would require deallocating yer shit too. 

    *crap = *cpy.crap; //making sure that it does not makes a shallow copy when assigning value 
    return *this; 
} 
1

이 주제에 대한 좋은 읽기입니다 What is the copy-and-swap idiom?

개체가 할당 된 메모리를 포함, 그래서 당신은 당신의 개체를 복사 할 때마다, 당신은 또한 새로운 메모리를 수행 할 필요가 할당하고, 귀하의 할당 내용을 복사하십시오. 그래서 복사 생성자에서 이러한 것들이 필요합니다. 컴파일러가 함수 호출을 통해 객체를 복사하려고 시도 할 때 복사 생성자가 자동으로 호출됩니다 (객체가 컨테이너에 배치 된 경우).

할당 연산자에 결함이 있습니다. 할당 연산자는 조금 더 많거나 조금 더해야하기 때문에 결함이 있습니다. 또 다른 하나 개의 객체를 할당 처리되어 있기 때문에 그것은

tnp = pnt; 

에 사용되는, 그것은 PNT의 메모리에 복사하기 전에 이전 TNP 객체의 메모리 할당 해제를 기존 할당 된 메모리를 사용하거나 처리하기 위해 중 하나가 필요합니다.