This question already has answers here:
-> usage in smart pointers
(2个答案)
7年前关闭。
像shared_ptr这样的智能指针可以像带有
这些书说
(2个答案)
7年前关闭。
像shared_ptr这样的智能指针可以像带有
*
和->
运算符的普通指针一样使用。这些书说
->
运算符返回shared_ptr存储的指针。因此,您可以使用它来访问此指针指向的对象。但是我在这里感到困惑。看下面的代码。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?
最佳答案
这是魔法。好吧,更像是一个特例。标准说
也就是说,对重载运算符的结果再次调用operator->
。如果该对象也被重载,它将以递归的方式进行下去,直到生成原始指针并调用内置operator->
。
这并不意味着结果不能是任意类型,而是可以,但是只能使用函数调用语法来调用它:
struct X {
int operator->() { return 42; }
};
int main()
{
X x;
x.operator->(); // this is OK
}
关于c++ - 运算符->智能指针的返回值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20583450/