【发布时间】:2014-01-18 19:08:54
【问题描述】:
我有一个Text 类,它具有某些返回指向自身的指针的方法,允许链接调用。 (原因是我只是喜欢链接的外观和感觉,老实说!)
我的问题是,在实践中通常哪个更好(在安全性 > 多功能性 > 性能方面)?返回和使用引用?还是返回并使用指针?
两者的例子,从指针版本开始:
class Text{
public:
Text * position(int x, int y){
/* do stuff */
return this;
}
Text * write(const char * string);
Text * newline();
Text * bold(bool toggle);
Text * etc();
...
};
textInstance.position(0, 0)->write("writing an ")->bold(true)->write("EXAMPLE");
textInstance.position(20, 100)
->write("and writing one across")
->newline()
->write("multiple lines of code");
相对于参考版本:
class Text{
public:
Text & position(int x, int y){
/* do stuff */
return *this;
}
Text & write(const char * string);
Text & newline();
Text & bold(bool toggle);
Text & etc();
...
};
textInstance.position(0, 0).write("writing an ").bold(true).write("EXAMPLE");
textInstance.position(20, 100)
.write("and writing one across")
.newline()
.write("multiple lines of code");
【问题讨论】:
-
没有性能差异。
标签: c++ pointers reference coding-style return