C :对象上的可复制视图
C++: copyable view on an object
我正在尝试制作一个处理图像的程序,其中我有一个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_ref
是const
。
我考虑使用智能指针而不是参考,但我找不到将智能指针用于已经存在的对象的方法。
我发现的一种解决方案是:
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;
};
默认复制构造函数和分配运算符将做正确的事情。
相关文章:
- 简单可复制与可简单复制
- reinterpret_cast,只读访问,简单的可复制类型,会出什么问题?
- 对于参加可复制和可移动类的访问者来说,应该有多少过载?
- 可变参数宏:无法通过"..."传递非平凡可复制类型的对象
- 为什么 std::atomic<std::string> 会给出微不足道的可复制错误?
- 我可以隐式地创建一个琐碎的可复制类型吗
- 是std::memcpy在不同的可复制类型之间的未定义行为
- 为什么一对常量是微不足道的可复制的,而对不是?
- 在一个微不足道的可复制结构中,移动语义应该实现吗?
- 防止作用域枚举可复制/可移动
- C :对象上的可复制视图
- 防御性地应用 std::move 到平凡可复制的类型是否不可取
- 为什么 std::function 本身是可复制构造的类型?
- 是否有范围::视图::转换的可修改视图版本
- C++不可复制的 lambda 的行为是可复制的
- 错误:无法通过'...'传递非平凡可复制类型的对象'class boost::filesystem::path'
- 不能让类是微不足道的可复制的。我做错了什么?
- 使用临时存储区复制普通的可复制类型:允许吗
- 使用realloc可以安全地重新分配琐碎的可复制对象的存储吗
- 为什么Boost.Asio处理程序必须是可复制的