unique_ptr 如何支持“点”和“箭头”调用以及未定义的方法?

One*_*ero 3 c++ unique-ptr

据我所知,在 C++ 中,任何对象上的任何方法调用都必须在其类定义中预先定义。因此,当我看的时候,它变得很有趣std::unique_ptr

似乎unique_ptr支持“点”(例如reset())和“箭头”操作。然而,“点”用于指针,而“箭头”用于对象/引用(我们可以这样做ptr->MethodThatTheEncapsulatedClassSupports())。那么如何unique_ptr既是指针又是对象呢?

第二个有趣的部分是,传递给的类unique_ptr可以是任意的。我可以在我的类中定义任何方法,并且似乎我们可以直接在unique_ptr实例上调用该方法。由于 C++ 没有像 Ruby 那样的动态方法调度机制(据我所知,C++ 方法调用是静态的并且必须定义,这很有意义,因为 C++ 直接编译成机器代码),那么这如何实现呢?

Mar*_*ork 5

之所以能够实现这一点,是因为operator->可以重载 来返回另一个对象或指针。然后递归地使用它operator->

 class Dest
 {
     public:
        void test() {
            std::cout << "Test Called\n";
        }
 };
 class Forward
 {
     Dest d;
     public: 
         Dest* operator->() {
             return &d;
         }
 };
 int main()
 {
     Forward  f;
     f->test();    // operator-> on the object `f` returns a pointer to
                   // an object of type `Dest*`. Now apply re-apply the
                   // operator-> to the result.
                   //
                   // Since it is already a pointer this means access the
                   // member (which in this case is a method call).
 }
Run Code Online (Sandbox Code Playgroud)

  • 由于`operator-&gt;()`返回一个指针,看来我们需要做`ptr-&gt;-&gt;method()`来代替?由于第一个“-&gt;”返回指针,第二个“-&gt;”对指针执行方法调用。 (3认同)