繁体   English   中英

C++ 传递 const 参考语法

[英]C++ Pass by const reference syntax

我知道通过引用传递与通过指针传递的主题被大量覆盖......我很确定我理解了所有细微差别,直到我读到这个:

http://carlo17.home.xs4all.nl/cpp/const.qualifier.html

内容为(以防链接失效)

The prototype for foobar can have any of the following footprints:
void foobar(TYPE);      // Pass by value
void foobar(TYPE&);     // Pass by reference
void foobar(TYPE const&);   // Pass by const reference

Note that I put the const to the right of TYPE because we don't know if TYPE (this is not a template parameter, but rather for instance a literal char*) is a pointer or not!

作者的意思是“请注意,我将 const 放在 TYPE 的右侧,因为我们不知道 TYPE ... 是否是指针!”

我读到的关于这个主题的所有内容都一致地说:

void foodbar(TYPE const &)

也等价

void foobar(const TYPE &)

如果我正确理解了作者,他/她是在说:

const int *X vs int * const X where 指针,X 本身是 const 而 X 指向的是 const?

如果是这样,这是真的吗?

如果 TYPE 是int*之类的#define ,则const的位置确实很重要。 在这种情况下,您将获得const int*int* const ,具体取决于const的位置。

如果 TYPE 是 typedef 或模板参数,则const将影响整个类型。

对我来说,这看起来更像是反对宏的另一个论点,而不是需要在声明中使用某种特定样式。

查看C++ FAQ Lite (如文章所示),您从右到左阅读指针声明。 因此,如果 TYPE 是指针,则 * 的位置确实会有所不同。 点击链接查看完整故事。

void foobar(TYPE const&);   // Pass by const reference

如果 TYPE 是指向类型 ABC 的指针,则

void foobar(ABC* const&)

不同于

void foobar(const ABC* &)

我相信这就是作者的全部内容。

编辑

如果 typedef 是指针,这也适用

typedef SomeStruct* pSomeStruct;
void foobar(pSomeStruct* const &); // const reference to a pointer
                                   // to a pointer to SomeStruct
void foobar(const pSomeStruct* &); // reference to a pointer
                                   // to a const pointer to const SomeStruct

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM