2017-05-19 2 views
2

서명되지 않은 char 배열에 대한 고유 포인터가 포함 된 클래스에 대한 복사 할당 연산자를 만들려고합니다. 여기 C++ 고유 포인터를 사용하는 클래스의 암시 적 삭제

는 모습입니다 같은 :

// equals operator 
     Image & operator=(const Image & rhs) { 
      if(data != nullptr) { 
       data.reset(); 
      } 

      data = std::unique_ptr<unsigned char[]>(new unsigned char[rhs.width * rhs.height]); 
      Image::iterator beg = this->begin(); 
      Image::iterator end = this->end(); 
      Image::iterator img_beg = rhs.begin(); 
      Image::iterator img_end = rhs.end(); 

      while(beg != end) { 
       *beg = *img_beg; 
       ++beg; 
      } 

      width = rhs.width; 
      height = rhs.height; 
      return *this; 
     } 

하지만 콘솔에 던져 다음과 같은 오류가 무엇입니까 :

imageops.cpp: In function ‘void handleInput(int, char**)’: 
imageops.cpp:26:16: error: use of deleted function 
‘YNGMAT005::Image::Image(const YNGMAT005::Image&)’ 
Image copy = img; 
      ^~~ 
In file included from imageops.cpp:6:0: 
image.h:14:8: note: ‘YNGMAT005::Image::Image(const YNGMAT005::Image&)’ 
is implicitly deleted because the default definition would be ill- 
formed: 
class Image { 
    ^~~~~ 
image.h:14:8: error: use of deleted function ‘std::unique_ptr<_Tp [], 
_Dp>::unique_ptr(const std::unique_ptr<_Tp [], _Dp>&) [with _Tp = 
unsigned char; _Dp = std::default_delete<unsigned char []>]’ 
In file included from /usr/include/c++/6/memory:81:0, 
      from image.h:7, 
      from imageops.cpp:6: 
/usr/include/c++/6/bits/unique_ptr.h:633:7: note: declared here 
    unique_ptr(const unique_ptr&) = delete; 
    ^~~~~~~~~~ 
makefile:5: recipe for target 'imageops.o' failed 
make: *** [imageops.o] Error 1 

나는 다음과 같이 드라이버 파일에서 이미지 객체를 생성하려고를 :

Image img; 
    string flag = cmds.at(1); 
    img.load(cmds.at(2)); 

    //cout << img; 
    Image copy = img; 

... 이미지 저장 포인터 std::unique_ptr<unsigned char[]> data;

많은 감사!

+2

[Rule of Five!] (http://en.cppreference.com/w/cpp/language/rule_of_three) (IOW, copy-ctor도 필요합니다). 또한'make_unique'를보십시오. –

+0

답이 아니라 다른 반복자도 증가시켜야한다고 생각합니다 :'img_beg'. 아니면 그냥'std :: copy'를 사용하십시오. – Galik

+0

당신이 가지고있는 것은 ** 아닙니다 ** 할당입니다 ** 초기화 **이므로 복사 생성자 *를 호출합니다. – Galik

답변

3

당신은 당신은 복사 할당 연산자를 호출하지 않는

Image copy = img; 

이있을 때. Image copy은 선언이므로 복사 생성자를 호출하는 것을 의미합니다. 즉, 클래스에 대한 복사 생성자를 정의해야합니다. 당신은, 당신은 하나를 제공하고자하고 Image는 기본 constructable 인 경우 복사 할당 연산자를 호출합니다

Image copy; 
copy = img; 

하지 않을 수 있다면.

+0

고마워요. 왜 두 번째 방법이 효과가 있었는지 궁금 해서요.하지만 첫 번째 방법은 효과가 없었습니다. –

+0

@MattYoung 문제가 없습니다. 기꺼이 도와주세요. – NathanOliver