操作符>智能指针的返回值 [英] the operator-> return value of smart pointers
问题描述
智能指针如shared_ptr可以像使用 *
和 - >
运算符的普通指针一样使用。
这些书说 - >
运算符返回shared_ptr存储的指针。所以你可以使用它来访问这个指针指向的对象。但我在这里感到困惑。看看下面的代码。
smart pointers like shared_ptr can be used like ordinary pointers with *
and ->
operator.
The books say that ->
operator returns the pointer that shared_ptr stores. So you can use it to access the object this pointer points to. But I am confused here. Look at the code below.
class A
{
public:
A(int v = 20){val = v;}
int val;
}
A* p1 = new A;
std::cout<<p1->val; //This is common sense
boost::shared_ptr<A> p2(new A);
std::cout<<p2->val; //This is right
//My question is that p2-> returns the pointers of the object, then maybe another
//-> should be used?
//like (p2->)->val?
推荐答案
好了,更像是一个特例。标准说
It's magic. Well, more like a special case. The standard says that
13.5.6类成员访问权限[over.ref]
1 operator->
应为不带参数的非静态成员函数。它实现了使用 - >
的类成员访问语法。
1 operator->
shall be a non-static member function taking no parameters. It implements the class member access syntax that uses ->
.
post fi x-expression - > templateopt id-expression
post fi x-expression - > pseudo-destructor-name
postfix-expression -> templateopt id-expression
postfix-expression -> pseudo-destructor-name
表达式 x-> m
解释为(x.operator->()) - > ;如果
T
的类对象 x
c $ c> T :: operator->()
存在,并且如果操作符被重载解决机制(13.3)选择为最佳匹配函数。
An expression x->m
is interpreted as (x.operator->())->m
for a class object x
of type T
if T::operator->()
exists and if the operator is selected as the best match function by the overload resolution mechanism (13.3).
也就是说,对重载的运算符的结果再次调用 operator->
。如果那个被重载,它会递归地继续,直到一个原始指针是结果,并且调用内置 operator->
。
That is, operator->
is called again on the result of the overloaded operator. And if that one is overloaded too, it goes on recursively until a raw pointer is the result and the built-in operator->
is called.
这并不意味着结果不能是任意类型 - 它可以是,但是你只能使用函数调用语法调用它:
That doesn't mean the result can't be any arbitrary type - it can be, but then you can only call it with the function call syntax:
struct X {
int operator->() { return 42; }
};
int main()
{
X x;
x.operator->(); // this is OK
}
这篇关于操作符>智能指针的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!