C++ 通过 const 引用语法传递

标签 c++ syntax reference

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

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 其中指针,X 本身是 const vs. X 指向的是 const?

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

最佳答案

如果 TYPE 是一个 #define 用于类似 int* 的东西,const 的位置很重要。在这种情况下,您将获得 const int*int* const,具体取决于 const 的位置。

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

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

关于C++ 通过 const 引用语法传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6234912/

相关文章:

c++ - 找不到 BOOST_FILESYSTEM(缺少 : BOOST_FILESYSTEM_LIBRARIES)

c++ - 如何在 C++ 中嵌入 Ruby?

c++ - SQL Server 按工作日查询,一天不从午夜开始

javascript - JavaScript 中的奇怪语法

javascript - IMACROS 将 iim 代码转换为 javascript 后出现代码错误

seo - 搜索引擎优化阅读 Material 和引用请求

python - 从 OpenGL 深度缓冲区获取世界坐标

PHP - 类数组中带有括号的奇怪语法错误

c# - 当所有玩家同名时查找 localPlayer

python - 如何在 TensorFlow 中取消引用 _ref 张量类型?