【发布时间】:2015-02-22 00:32:05
【问题描述】:
所以我有一个我认为很常见的涉及对象的 C++ 问题 作品。问题域是这样的:一个动画 gif 可以有很多 框架,而绘制框架取决于 Gif 的其他内容的上下文 帧。
所以我有这个模型(对于这个问题进行了很多简化,但应该 说明):
class Gif {
std::vector<Frame> _frames;
// Makes Frame objects from file and puts them in _frames
Gif(const char* file){...};
// For clarity, works and copies the _frames member
Gif(const Gif& other) = default;
};
class Frame {
Frame(...){
// Make a frame object
}
void draw(const Gif& context){
// draws self considering context's other frames
}
};
这可行,但为了简单起见并避免在其中绘制 Frame
错误的上下文,我希望 draw 方法不会采用 context 参数。所以我想用const 创建框架
参考会员_context:
class Frame {
const Gif& _context;
// Make a frame object
Frame(const Gif& context) _context(context){...}
// Explicit default copy-constructor, for clarity. Breaks horribly
// when called from Gif's copy constructor, since the new Frame will
// reference the wrong context, which might be deleted.
Frame(const& Frame other) = default;
void draw(){
// draws self considering _context's other frames
}
};
这可以编译,但在复制 Gifs 时会严重中断。 Frame
新 Gif 的对象是副本,但它们引用
错误的上下文,通常已被删除。
我认为 const 引用成员对于
您打算复制的对象...我应该使用指针和
为自定义Gif 的复制构造函数的主体中的新Frames 显式重置它?
如果有,是什么类型的 指针(原始/智能)?是不是有一个很好的 C++11 技术来制作 这会“自动”发生吗?
或者我应该打破循环依赖以及如何打破?
编辑(感谢 KillianDS):为了清楚起见,您从 gif1 开始,带有一些指向 gif1 的帧(frame1_1,frame1_2,...),现在您想将 gif1 复制到 gif2,并带有复制的帧(frame2_1,frame2_2 ,...) 但那指向 gif2?
【问题讨论】:
-
为了清楚起见,您从
gif1开始,带有一些指向gif1的帧 (frame1_1, frame1_2, ...),现在您想将gif1复制到gif2并复制帧 (@ 987654338@) 但指向gif2? -
是的@KillianDS,正是
-
Gif类的用户似乎可以访问Frame类的对象(引用)。为什么不让Gif发布某种指针类型FramePointer,其中包含Gif const* context和Frame* frame? -
@dyp 可以复制这个新对象吗?如果是,然后
Gif和Frame消失怎么办?如果它不可复制,也许这个想法可行,你能把它变成一个答案吗?