【问题标题】:Should a const member function return a const or non-const?const 成员函数应该返回 const 还是非常量?
【发布时间】:2013-01-25 22:32:18
【问题描述】:
struct Type
{
  auto opBinary(string op)(Type other) const {
    return Type();         // #1 return type is Type
    return typeof(this)(); // #2 return type is const(Type)
  }
}

unittest
{
  Type t1, t2;
  auto t3 = t1 + t2;
}

t1.opBinary!("+")(t2) 中,t1 变为常量,而t2 保持非常量。 opBinary的返回类型应该是Type还是const(Type),为什么?

const(T) 是一个超类型,所以也许它应该返回一个const,但我在实践中几乎没见过这种情况。在处理使用这些类型或被这些类型使用的类型和函数的层次结构时,事情也会变得相当复杂。

【问题讨论】:

    标签: constants d


    【解决方案1】:

    由于这里的返回值是一个新对象,我会说它是非常量的。作为新的,它可以安全地修改,所以没有理由用 const 不必要地限制它。

    如果您要返回现有对象的一部分,则需要使用 inout 而不是 const。 inout 表示对象的 constness 也会去返回值。

    inout(Type) opBinary(string op)(Type other) inout {
        return whatever;
    }
    

    现在如果你使用一个 const(Type) 对象,返回也是 const,如果它被一个可变对象调用,返回也是可变的。

    【讨论】:

      【解决方案2】:

      返回类型应该是 T 还是 const(T)? 任何都可以。

      哪个更好?取决于你的预期行为。

      opBinary 上的

      const 限定符仅表示隐藏的“this”参数是 const。仅此而已,仅此而已。它并不暗示有关返回类型的任何内容。这一切都归结为非常简单的选择:

      struct Type
      {
          int a;
          auto opBinary(string op)(Type other) const
                 if (op == "+")
          {
              return Type(this.a + other.a);
          }
      }
      
      void main()
      {
          Type first, second;
          (first + second).a = 42; // Do you want to allow this?
                                   // Yes -> return non-const
                                   // No -> return const
      }
      

      如果您想保留参数的限定符,请使用 inout(请参阅 Adams 答案)或手动检查限定符以获得更复杂的选择。

      无论选择哪一种,请记住自动类型推断:

      auto third = first + second;
      third.a = 42; // Error if returns const
      
      Type fourth = first + second;
      fourth.a  = 42; // Fine in both cases, struct was copied
      

      最后是关于你作为类型设计师的意图,类/结构应该如何表现。

      【讨论】:

        猜你喜欢
        • 2021-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-18
        • 2015-06-10
        • 1970-01-01
        相关资源
        最近更新 更多