2013-10-01 5 views
11

Due to this bug in Visual Studio 2013私は独自の移動コンストラクタを提供し、派生クラスの割り当てを移動する必要があります。しかし、私はどのように基本クラスの適切な移動関数を呼び出すか分からない。ここでこの派生クラスの移動割り当て関数はどのように記述しますか?

はコードです:

#include <utility> 

// Base class; movable, non-copyable 
class shader 
{ 
    public: 
     virtual ~shader() 
     { 
      if (id_ != INVALID_SHADER_ID) 
      { 
       // Clean up 
      } 
     } 

     // Move assignment 
     shader& operator=(shader&& other) 
     { 
      // Brett Hale's comment below pointed out a resource leak here. 
      // Original: 
      // id_ = other.id_; 
      // other.id_ = INVALID_SHADER_ID; 
      // Fixed: 
      std::swap(id_, other.id_); 
      return *this; 
     } 

     // Move constructor 
     shader(shader&& other) 
     { 
      *this = std::move(other); 
     } 

    protected: 
     // Construct an invalid shader. 
     shader() 
      : id_{INVALID_SHADER_ID} 
     {} 

     // Construct a valid shader 
     shader(const char* path) 
     { 
      id_ = 1; 
     } 

    private: 
     // shader is non-copyable 
     shader(const shader&) = delete; 
     shader& operator=(const shader&) = delete; 

     static const int INVALID_SHADER_ID = 0; 

     int id_; 
     // ...other member variables. 
}; 

// Derived class 
class vertex_shader final : public shader 
{ 
    public: 
     // Construct an invalid vertex shader. 
     vertex_shader() 
      : shader{} 
     {} 

     vertex_shader(const char* path) 
      : shader{path} 
     {} 

     // The following line works in g++, but not Visual Studio 2013 (see link at top)... 
     //vertex_shader& operator=(vertex_shader&&) = default; 

     // ... so I have to write my own. 
     vertex_shader& operator=(vertex_shader&&) 
     { 
      // What goes here? 
      return *this; 
     } 

     vertex_shader(vertex_shader&& other) 
     { 
      *this = std::move(other); 
     } 

    private: 
     // vertex_shader is non-copyable 
     vertex_shader(const vertex_shader&) = delete; 
     vertex_shader& operator=(const vertex_shader&) = delete; 
}; 

int main(int argc, char* argv[]) 
{ 
    vertex_shader v; 

    // later on 
    v = vertex_shader{ "vertex_shader.glsl" }; 

    return 0; 
} 

は、派生クラスでの移動の割り当て機能はどのようなものになるはずですか?

+2

*これはSTDを= '使用に関する興味深い記事::移動(その他)'移動コンストラクタを実装するためにします。http://のstackoverflowを。 com/questions/17118256/implementation-move-constructor-by-call-move-assignment-operator – goji

+0

@Troy、フィードバックに感謝します。それは私が最初にそのスタイルに変更したMicrosoftの記事でした。私が想定しているMicrosoftを無視する別の理由。 :) –

+0

それは動作しますが、他の質問は、移動割り当ての効率性の利点の一部を無効にすることを示しています。私が推測することについて考えてみてください:) – goji

答えて

23

あなただけの基本クラスムーブ代入演算子を呼び出す必要があります。

vertex_shader& operator=(vertex_shader&& rhs) 
    { 
     shader::operator=(std::move(rhs)); 
     return *this; 
    } 
関連する問題