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;
}
究竟應該在派生類中的樣子,此舉分配功能?
有趣的帖子上使用'*此=的std ::移動(其他)'來實現移動構造函數:HTTP://計算器。 com/questions/17118256/Implement-move-constructor-by-calling-move-assignment-operator – goji
@Troy,謝謝你的反饋。微軟的文章首先讓我改變了這種風格。我想忽略微軟的另一個原因。 :) –
它的作品,另一個問題只是概述它否定了移動作業的一些效率優勢。只是想一想我猜:) – goji