C ++-重载结构取消引用运算符,并在unique_ptr中使用它

问题描述 投票:1回答:1

我有一个实现类和一个包装器类,我想通过带有结构取消引用(->)运算符的包装器类访问实现类实例。到目前为止,没有问题。

class Implementation
{
  public:
    doSomething();
}

class Wrapper
{
  public:
    Implementation* operator->() {
      return _implPtr.get();
    }
  private:
    std::shared_ptr<Implementation> _implPtr;
}

[当我按如下方式使用时可以使用:

Wrapper wrapper;
wrapper->doSomething();

但是当我将包装器类与unique_ptr一起使用时,编译器会引发错误:

auto wrapper = std::make_unique<Wrapper>();
wrapper->doSomething();

错误是“'类包装器'没有名为'doSomething'的成员。”

在这种情况下,我如何访问实现类?

c++ smart-pointers dereference
1个回答
2
投票

[std::unique_ptr(和std::shared_ptr)具有自己的operator->以返回其持有的指针。

您的失败代码实际上是在这样做:

operator->

确实,auto wrapper = std::make_unique<Wrapper>(); //wrapper->doSomething(); Wrapper *ptr = wrapper.operator->(); ptr->doSomething(); // ERROR! 类中没有doSomething()方法。

要做您想做的事情,您需要取消引用Wrapper指针以访问实际的Wrapper*对象,然后可以调用其自己的Wrapper以访问其operator->指针,例如:

Implementation*

基本上是这样做的:

auto wrapper = std::make_unique<Wrapper>();
(*wrapper)->doSomething();
© www.soinside.com 2019 - 2024. All rights reserved.