operator* 已经返回一个引用:
T& ref = *ptr;
Run Code Online (Sandbox Code Playgroud)
或者,我想我可以给出一个更有意义的例子:
void doSomething(std::vector<int>& v)
{
v.push_back(3);
}
auto p = std::make_shared<std::vector<int>>();
//This:
doSomething(*p);
//Is just as valid as this:
vector<int> v;
doSomething(v);
Run Code Online (Sandbox Code Playgroud)
(请注意,使用引用自由对象的引用当然是无效的.保持对对象的引用与保持shared_ptr实例的效果不同.如果shared_ptr实例的计数降为0,则对象将被释放,无论有多少引用引用它.)