c++ - 对象初始化: Init method or stream operator?

标签 c++ initialization

Game Coding Complete 4th ed. by Mike McShaffry and David Graham (67-68) 说类应该使用流来初始化对象:

class AnimationPath
{
    public:
    AnimationPath();
    Initialize(std::vector<AnimationPathPoint> const & srcPath);
    Initialize(InputStream & stream);
    //of course lots more code follows.
};

This class has a default constructor and two ways to initialize it. The first is through a classic parameter list, in this case, a list of AnimationPathPoints. The second initializes the class through a stream object. This is cool because you can initialize objects from a disk, a memory stream or even the network....

(Mr. Graham, the author of the chapter containing the quote, goes on the explain why using a stream as an argument to a constructor is bad. Streams could fail and your object is in a failed state.

我的问题是,不是使用此策略,而是为什么不使用流运算符 operator<<operator>>代替或补充 Initialize方法。 (Initialize 方法甚至可以只是流运算符的委托(delegate)。)

差异是语义上的还是有合理的理由使用其中之一?

最佳答案

operator<<operator>>是令人厌恶的,也是 C++ IOStreams 库的最大错误之一。切勿复制该模式。采取明确的 std::istream& (或您的框架的等效框架)更有意义。

一种更简洁的方法(尽管并不总是最可行)是拥有一个完全独立的 AnimationPathSerializer处理将流映射到 AnimationPath对象。保持每种类型/对象很小并且只关注一个问题。动画不需要知道如何加载或保存自身以成为动画,并且有时您可能希望支持几种完全不同的具有非常不同语义的序列化格式(因此单个通用流类型或单个序列化对象中的接口(interface)没有意义)。

关于c++ - 对象初始化: Init method or stream operator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24225128/

相关文章:

c++ - 使用 OpenCV 在 iOS 应用程序中进行圆检测

c++ - 拆分 malloc 内存空间

arrays - 有没有办法不必两次初始化数组?

java - 如何在没有构造函数的情况下初始化类?

c - 将字符串初始化为空终止以避免 memset

gcc - 用特定值填充向量 (SSE2) 的最快方法。模板友好

c++ - 2 位输入的表达式树

c++ - auto* 在编译时有用还是 auto 关键字就足够了?

c++链表模板和节点

c++ - "hello"和 {"hello"} 有什么区别?