gpt4 book ai didi

c++ - 如何为这个派生类编写 move 赋值函数?

转载 作者:IT老高 更新时间:2023-10-28 22:34:19 25 4
gpt4 key购买 nike

Due to this bug in Visual Studio 2013 ,我需要为派生类提供自己的 move 构造函数和 move 赋值。但是,我不知道如何为基类调用适当的 move 函数。

代码如下:

#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;
}

派生类中的 move 赋值函数应该是什么样子的?

最佳答案

你只需要调用基类 move 赋值运算符:

    vertex_shader& operator=(vertex_shader&& rhs)
{
shader::operator=(std::move(rhs));
return *this;
}

关于c++ - 如何为这个派生类编写 move 赋值函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19109392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com