2017-05-19 6 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オブジェクトを作成しようとしています:

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はデフォルト構築可能である場合、コピー代入演算子を呼び出します

Image copy; 
copy = img; 

をしないことができれば。

+0

ありがとうございました。私はなぜ第2の方法が働いたのだろうと思っていましたが、第1の方法は効果がありませんでした。 –

+0

@MattYoung問題ありません。喜んで助けてください。 – NathanOliver

関連する問題