C :对象上的可复制视图

C++: copyable view on an object

本文关键字:可复制 视图 对象      更新时间:2023-10-16

我正在尝试制作一个处理图像的程序,其中我有一个image对象和一个image_view对象,该对象引用图像中的矩形区域:

class image_view;
class image
{
    public:
        image(int width, int height);
        operator image_view() const;
    private:
        int m_width;
        int m_height;
        std::vector<pixel> m_pixels;
};
class image_view
{
    public:
        image_view(const image& ref, point origin, int width, int height);
        image_view(image_view view, point origin, int width, int height);
    private:
        const image& m_ref;
        point m_origin;
        int m_width;
        int m_height;
};

但是,当我尝试复制image_view时,编译器告诉我,由于非静态成员参考,operator=成员函数已被删除。我天真地尝试通过m_ref = other.m_ref来使自己的会员功能,但由于m_refconst

我考虑使用智能指针而不是参考,但我找不到将智能指针用于已经存在的对象的方法。

我发现的一种解决方案是:

image_view& image_view::operator= (const image_view& other)
{
    *this = image_view(other);
    return *this;
}

这是一个编译,但这是个好主意吗?(我可能是错的,但是我对将东西分配给*this感到很难5?

的规则

如果要表达一个非持有的非零用包装器,该包装可以重新启用分配,最简单的方法是使用std::reference_wrapper

class image_view
{
public:
    image_view(const image& ref, point origin, int width, int height);
    image_view(image_view view, point origin, int width, int height);
private:
    std::reference_wrapper<image const> m_ref;
    point m_origin;
    int m_width;
    int m_height;
};

默认复制构造函数和分配运算符将做正确的事情。