【问题标题】:Const/ref problem in DD 中的 const/ref 问题
【发布时间】:2011-08-07 21:49:25
【问题描述】:

我正在尝试在 D 中实现我自己的范围,但我在使用它的 .front() 方法时遇到了问题。

编辑:

我需要返回值是ref

  • 如果我把它设为const,那么返回的对象将是一个副本,这不是我想要的。

  • 如果我将其设为const,那么我根本无法在我的范围的const 副本上使用.front

我该如何解决这个问题?

struct MyRange(T)
{
    T[] buf;

    @property ref T front() { return this.buf[0]; }  // No error, but not const
    @property ref T front() const { return this.buf[0]; }  // Errors
    @property T front() const { return this.buf[0]; }  // No error, but a copy
    
    // Can't have all three
}

【问题讨论】:

    标签: constants d


    【解决方案1】:

    试试这个:

    struct MyRange(T)
    {
        T[] buf;
    
        @property ref T front() { return this.buf[0]; }
        @property ref const(T) front() const { return this.buf[0]; }
    }
    

    您的示例中的问题是您创建了 front const 但没有返回值,编译器不会让您像这样转义对 const 数据的可变引用。

    现在,我要指出,一般来说,您不应该期望 const 范围能很好地工作。就其本质而言,它们需要是可变的才能对其进行迭代(因为您不能在 const 范围内调用 popFront),因此除了使用 front 和 @987654325 之外,您将无法做太多事情@ 带有 const 范围。如果您可以将 const 范围隐式转换为 tail-const 范围,情况就不会那么糟糕,但这仅适用于数组,而且还没有人想出一种对一般范围进行此操作的好方法。所以不幸的是,此时 const 范围基本上是无用的。

    【讨论】:

      【解决方案2】:

      如果你为front创建一个单独的setter会怎样:

      @property T front() const { return this.buf[0]; }//const
      @property void front(T t) { this.buf[0]=t; }//allows assign when needed
      

      这在你需要的范围内吗?

      【讨论】:

      • 不——那是不同的。你不能那样取它的地址。此外,它看起来甚至无法编译——T 不是 const,但 this.buf[0] 是。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-17
      • 2021-12-13
      • 2011-10-24
      • 2015-10-02
      • 1970-01-01
      • 2010-12-07
      相关资源
      最近更新 更多