了解 void f(const T¶m) 中的参数类型

Understand the type of param in void f(const T& param)

本文关键字:参数 类型 param void const 了解      更新时间:2023-10-16

参考:有效的现代C++第 4 项。

https://github.com/BartVandewoestyne/Effective-Modern-Cpp/blob/master/Item04_Know_how_to_view_deduced_types/runtime_output02.cpp

class Widget {};
template<typename T>                // template function to
void f(const T& param)              // be called
{
}
std::vector<Widget> createVec()    // factory function
{
    std::vector<Widget> vw;
    Widget w;
    vw.push_back(w);
    return vw;
}
int main()
{
    const auto vw = createVec();        // init vw w/factory return
    if (!vw.empty()) {
      f(&vw[0]);                        // call f
      // ...
    }
}

根据本书,Tparam的类型分别如下:

T = class Widget const *
param = class Widget const * const &

我很难理解为什么param是上面定义的f(const T& param)给定类型。

这是我的理解,

T = class Widget const *

因此f(const T& param)变为以下内容:

f(const const Widget * & param) .

为什么真正的param类型是Widget const * const &

问题>为什么参数的真正类型是 Widget const * const 和代替?

我不是真正的专家,但是...因为T是一个指针,如果你写const T &(这是T const &因为规则是const应用于左侧的元素或右侧的元素,因为左侧没有元素)你正在强加完整的T类型,所以指针, 是恒定的。

要强制指针是恒定的,您必须在*的左侧强加cont

简而言之:const T &等同于T const &;有了const Widget * TT const &变得const Widget * const &,或者,如果你愿意,可以Widget const * const &

你对常量指针指向常量(然后是常量指针到常量)感到困惑。

注意*const的位置,例如 Widget const *是指向常量(Widget)的非常量指针,Widget * const是指向非常量(Widget)的常量指针,Widget const * const是指向常量(Widget)的常量指针。

对于 T = Widget const *,它是指向 const 的非常量指针;请注意,对于 const Tconst 限定在T即指针本身,而不是指向的对象,那么const T将被Widget const * const