- >在智能指针中的使用 [英] -> usage in smart pointers

查看:111
本文介绍了 - >在智能指针中的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的智能指针实现,如下面的代码片段1所示。和第二个片段中名为Dummy的虚拟测试类。代码片段3显示了我们如何利用这个简单的智能指针访问函数foo()。

I have a simple smart pointer implementation shown in code snippet 1 below. And a dummy test class named Dummy in the 2nd snippet. The code snippet 3 shows how we can utilize this simple smart pointer to access the function foo().

我的问题是关于我们通过使用 - >运算符调用类Dummy中的函数foo()的方式。 - >运算符已经返回一个指向原始指针的指针。所以,我认为,为了使我们能够调用函数foo(),我们需要对返回的原始指针执行第二 - >操作。然而,许多资源说,单一使用 - >运算符就足够了。

My question is about the way we invoke the function foo() in class Dummy by using the -> operator. -> operator already returns a pointer to the raw pointer. So, I think, in order for us to be able to invoke function foo(), we need to perform a second -> operation on the returned raw pointer. However, many resources say that a single use of the -> operator is sufficient simply.

简单来说,我认为正确的调用应该像下面这样:
(dummy - >) - > foo

Briefly, I think that correct call should be like the following: (dummy->)->foo();

但是,像这样的调用 - > foo()工作正常。有人可以解释我为什么(dummy - >) - > foo()不正确吗?

However, the call like this dummy->foo() works fine. Can someone explain me why (dummy->)->foo() is incorrect? Perhaps, I have a conceptual misunderstanding but I would like to know the concept right.

CODE SNIPPET 1(SMART POINTER Class)

template <typename T>
class SmartPointer
{
 private:
    T* mRawPointer;

 public:
    SmartPointer(T* thePointer) : mRawPointer(thePointer) {}
    ~SmartPointer() { delete mRawPointer;}

    T& operator* () const { return *mRawPointer; }

    T* operator-> () const { return mRawPointer; }

};

CODE SNIPPET 2(Dummy类)

class Dummy
{
 public:
   foo() {......}
};

CODE SNIPPET 3(问题中的交换意见) b
$ b

CODE SNIPPET 3 (INVOCATTION ALTERNATIVES IN QUESTION)

SmartPointer<Dummy> dummy(new Dummy());

(dummy->)->func(); 
//I think the above is correct cause we need to make a second dereference on the 
//returned raw pointer
//OR
dummy->func();


推荐答案

..


表达式x-> m解释为(x.operator - >()) - > m $ b如果T :: operator - >()存在,并且如果操作符是
,则通过重载分辨率选择为最佳匹配函数的$ T类型的对象x
机制

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

这篇关于 - &gt;在智能指针中的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆