c++ - 重载的 const 和非 const 类方法在 C++ 中返回引用

标签 c++ class constants const-cast

<分区>

我在 C++ 中有一个数据结构类,它带有某个对象(可能很大)的访问器,并且我有使用此访问器的 const 和非 const 方法,因此我需要重载它。我正在寻找对下面代码的批评 - 也许有一种方法可以完成同样的事情但更干净?

在我的理解中,有两种方法可以在不复制访问器代码的情况下实现这一点,在下面的例子中,get() 方法。我不确定这两种方法中的任何一种是否存在严重问题,我需要一些指导

我喜欢方法 A,因为:

  • 只有一个const_cast
  • 方法 get() 的常量版本返回一个拷贝
  • 非常量方法直接获取非常量引用

我不喜欢方法 A,因为:

  • 非 const 方法 get() 仅按约定为 const,(未经编译器检查)
  • 更难获得常量引用,但并非不可能

我喜欢方法 B,因为:

  • const 方法 get() 的 const-ness 由编译器检查
  • 返回对象的拷贝由用户控制

我不喜欢方法 B,因为:

  • 需要两个难以阅读的 const_casts

这是两种情况的(最小)示例代码。

/**
 * summary:
 * Two classes with an overloaded method which is
 * guaranteed (by contract) not to change any
 * internal part of the class. However, there is a
 * version of this method that will return a non-const
 * reference to an internal object, allowing the user
 * to modify it. Don't worry about why I would ever
 * want to do this, though if you want a real-world
 * example, think about std::vector<>::front()
 *
 * The difference between A and B can be summarized
 * as follows. In both cases, the second method merely
 * calls the first, wrapped with the needed
 * const_cast's
 *
 * struct A {
 *     int& get();
 *     int  get() const;
 * };
 *
 * struct B {
 *     const int& get() const;
 *           int& get();
 * };
 *
 **/

struct A
{
    int _val;

    A() : _val(7) {};

    // non-const reference returned here
    // by a non-const method
    int& get()
    {
        // maybe lots of calculations that you do not
        // wish to be duplicated in the const version
        // of this method...
        return _val;
    }

    // const version of get() this time returning
    // a copy of the object returned
    int get() const
    {
        // CONST-CAST!!?? SURE.
        return const_cast<A*>(this)->get();
    }

    // example of const method calling the
    // overloaded get() method
    int deep_get() const
    {
        // gets a copy and makes
        // a copy when returned
        // probably optimized away by compiler
        return this->get();
    }
};

struct B
{
    int _val;

    B() : _val(7) {};

    // const reference returned here
    // by a const method
    const int& get() const
    {
        // maybe lots of calculations that you do not
        // wish to be duplicated in the non-const
        // version of this method...
        return _val;
    }

    // non-const version of get() this time returning
    // a copy of the object returned
    int& get()
    {
        // CONST-CAST!? TWO OF THEM!!?? WHY NOT...
        return const_cast<int&>(const_cast<const B*>(this)->get());
    }

    // example of const method calling the
    // overloaded get() method
    int deep_get() const
    {
        // gets reference and makes
        // a copy when returned
        return this->get();
    }
};


int main()
{
    A a;
    a.get() = 8;  // call non-const method
    a.deep_get(); // indirectly call const method

    B b;
    b.get() = 8;  // call non-const method
    b.deep_get(); // indirectly call const method
}

最佳答案

成员函数的常量性应根据以下问题确定:成员函数是否在上下文中用于修改对象?(成员直接修改对象,或返回引用/指向内部数据的指针,以便外部调用者可以修改该对象)。如果是,则将其设置为非常量,否则将其设置为常量。

编译器将正确地选择仅在 constness 上不同的重载。但是,返回类型不用于重载决议。此外,按值/按引用返回应该仅根据预期成本和您要返回的内容的预期所有权来决定。幸运的是,C++11 通过提供 move semantics 让生活变得更轻松.这意味着您可以愉快地按值返回大型数据结构。如果引用的对象将比外部调用者活得更久,则仅通过引用返回。

在我看来,你的 int& get() 应该重命名为 void set(int) 并且你可以拆分你的 int get() const 到计算助手和适当的 get()

class C
{
    int val_;
public:
    void modify()   { /* some expensive computation on val_ */ }
    int get() const { return val_; }
    void set(int v) { val_ = v_; }
};

或者,如果您想保留 get() 函数,您可以这样做

class D
{
int val_;
public:
    void modify()    { /* some expensive computation on val_ */ }
    int get() const  { modify(); return val_; }
    int& get()       { modify(); return val_; } // no const-cast needed
};

关于c++ - 重载的 const 和非 const 类方法在 C++ 中返回引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16950003/

相关文章:

c++ - 使用 decltype 推导局部变量的类型时,局部变量是左值吗?

swift - 如何在类中包含初始值设定项但仍然能够访问类的值

单击按钮时 JavaScript 更改类的颜色

c++ - Win32 API GetMessage()

c# - 全局与成员函数

java - 如何从jar文件动态加载类

C 使用常量声明二维数组

java - 在多个类中共享常量(android扫雷)

php - 无法使用 namespace 从动态类中获取常量

c++ - 如何找出所有闭源应用程序正在写入的位置?