c++ - 方法调用链接;返回指针还是引用?

标签 c++ pointers reference coding-style return

我有一个 Text 类,它有一些方法可以返回一个指向自身的指针,允许链接调用。 (老实说,我只是喜欢链接的外观和感觉!)

我的问题是,哪个在实践中通常更好(在安全性 > 多功能性 > 性能方面)?返回和使用引用文献?还是返回并使用指针?

两者的一个例子,从 Pointer 版本开始:

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");

最佳答案

指针和引用的区别很简单:指针可以为空,而引用不能。

检查您的 API,如果返回 null 有意义(可能表示错误),请使用指针,否则使用引用。如果您确实使用指针,则应添加检查以查看它是否为空(此类检查可能会降低您的代码速度)。

这里看起来引用更合适。

关于c++ - 方法调用链接;返回指针还是引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20864260/

相关文章:

c++ - 正确包括在 opencv 2.3 中使用新的 C++ API

C - 字符串到莫尔斯电码程序中的段错误

复制构造函数中的 C++ vector 数组

c++ - 使用指针对用户定义对象的 C++ 数组进行排序?

c++ - 有没有办法绑定(bind) template<template> 参数?

c# - 线性代数库

c++ - 如何将数组中的值复制到新数组中?

JavaScript 封装数据的闭包可以被规避吗?

swift - 为什么值类型的常量实例不能更改其属性而引用类型的常量实例可以?

c++ - C++ 中的临时对象