如果 x 是对 unique_ptr 的引用,则 *x 是"reference to element pointed to" ?



refPtrInt是指针的引用:

int *& refPtrInt;

*refPtrIntint还是对int的引用?

编辑:谢谢你对refPtrInt的回答。实际上,我最初的问题是关于Stroustrup (c++导览,第5.5节)中的这段代码:

template<typename C, typename Oper>
void for_all(C& c, Oper op) // assume that C is a container of pointers
{
    for (auto& x : c)
    op(*x); // pass op() a reference to each element pointed to
}
vector<unique_ptr<Shape>> v;
// populate v with some kinds of Shape
for_all(v, [](Shape& s){ s.draw(); });

注释" pass op() a reference to each element pointed to "也来自Bjarn Stroustrup。所以,*x显然是对Shape的引用,当x是对unique_ptr<Shape>的引用时…对吗?

没有区别。形式上,表达式不能有引用类型。不那么正式的,我们可以将任何表达式描述为引用对象的。这个用法出现在你引用的教科书中。

形式上,表达式*refPtrInt的类型为int,其值类别为lvalue,指定一个int对象。

x的类型为unique_ptr<Shape>。这意味着*x调用重载的操作符函数:

typename std::add_lvalue_reference<T>::type std::unique_ptr::operator*() const;

返回类型为Shape&的函数。通常会说"该函数返回对Shape的引用",但同样重要的是要理解,当在表达式中使用函数调用时,结果(这里的*x)是类型为Shape的表达式,值类别为lvalue

int。"参考"位无关紧要。您正在更改指针,它指向int

相关内容

最新更新