refPtrInt是指针的引用:
int *& refPtrInt;
*refPtrInt
是int
还是对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
。