【发布时间】:2019-10-03 11:20:34
【问题描述】:
给定以下类型
// interface and implementation used in one part of the codebase
struct Image
{
virtual std::vector<uint8_t>& GetData () = 0;
};
struct VecImage : public Image
{
std::vector<uint8_t> mData;
std::vector<uint8_t>& GetData () { return mData; }
};
// used in another part of the codebase
struct PtrImage
{
std::shared_ptr<uint8_t> mData;
PtrImage (std::shared_ptr<Image> pIm);
};
以下构造函数是将Image 转换为PtrImage 的合理且正确的方法吗?
PtrImage::PtrImage (std::shared_ptr<Image> pIm)
{
struct im_deleter
{
std::shared_ptr<Image> keepAlive;
void operator () (uint8_t* ptr)
{
keepAlive.reset ();
}
};
mData = { &pIm->GetData()[0], im_deleter { pIm } };
}
PtrImage 用作“值类型”,它是按值传递的,而Image 仅在 shared_ptrs 中传递。
【问题讨论】:
-
随着答案中 cmets 的发展,我越来越觉得我们正在讨论 XY problem。你实际上想用这个结构解决什么问题?
-
代码库周围有两种“图像”类型,我试图弄清楚是否可以在没有副本的情况下安全地将一种转换为另一种。 (而不是重写大量代码以在任何地方只使用一种图像类型。)
-
您如何表示系统中的实际图像数据?我的意思是:如果你有e。 G。 JPEG数据,你会解码吗?如果您有一个通用的内部图像表示,那么我宁愿为每种图像类型编写一个加载器和一个存储类,每个都会加载数据并将其转换为内部表示(例如,每个像素设置一个 RGB 或 RGBA),而您finally 只会在内部处理一种图像类型。商店只会做相反的事情。然后图像转换可能如下所示:
LoaderJPG l; Image i = l.load("path to file"); StorerPNG s; s.store(i, "path to file"); -
如果您想将图像绘制到屏幕上或想要转换,无论如何您都需要所有图像类型的共同点......当然,上面的示例也可以使用智能指针完成,如果那更合适;我个人更愿意使用图像类inside 的智能指针,并将图像本身作为(const)引用或在某些特定情况下按值传递。如果您选择智能指针:让加载程序返回
std::unique_ptr- 将唯一指针移动到共享指针比在不需要时共享开销更有效。
标签: c++ shared-ptr value-type