【问题标题】:C++: -> operator overloading: Handle const / nonconst access differentlyC++:-> 运算符重载:以不同方式处理 const / nonconst 访问
【发布时间】:2011-03-31 18:18:51
【问题描述】:

我正在构建一个引用计数系统并定义了一个原型模板类,它表示对将要使用的对象的所有引用。

我被卡住的地方是我必须区分通过引用访问这些对象的 const 和非 const 访问。如果访问是 const(只读,或者底层对象的调用方法被标记为 const),一切正常 - 但如果不是 - 可能必须先创建对象的副本。

我的参考类的简化版本:

template< class T >
class CRef
{
protected:
    T* ptr;

public:

    T* const* operator ->() const { return ptr; };
    T* operator        ->()       { printf( "Non-const access!" ); return ptr; };

};

问题是,只有非常量 -> 运算符重载函数被调用,即使在访问底层对象类型的 const 函数时也是如此。

  • 如何正确调用常量解引用重载函数?

【问题讨论】:

    标签: c++


    【解决方案1】:

    const 对象在 const 对象上调用。如果您想调用 const ->,请将您必须的对象引用转换为 const 或提供一种方法来获取对象的 const 版本。

    【讨论】:

      【解决方案2】:

      const/非常量原则上不能用于区分读写访问。

      你在这里不走运。实现这一点的唯一方法是通过operator -&gt; 返回的代理对象并通过隐式转换处理读取:

      返回的代理定义了一个operator T(隐式转换),当它被分配给另一个对象时被调用,而operator =(T const&amp;) 在被分配给它时被调用。

      template <typename T>
      class CRef {
          …
          CRefElementProxy<T> operator ->() const { return CRefElementProxy<T>(this); };
      
          friend CRefElementProxy;
      };
      
      template <typename T>
      class CRefElementProxy {
          operator T const*() const { return parent->ptr; }
          CRefElementProxy operator =(T const* value) {
              printf("Non-const access!");
              return parent->ptr;
          }
      };
      

      这只是一个伪代码草稿。真正的版本看起来要复杂一些。

      【讨论】:

        【解决方案3】:

        一旦指针被返回,就无法知道它做了什么。

        【讨论】:

          猜你喜欢
          • 2011-03-28
          • 2011-01-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-23
          • 1970-01-01
          相关资源
          最近更新 更多