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