代码之家  ›  专栏  ›  技术社区  ›  user272735

使用writeln打印结构时额外为null

d
  •  0
  • user272735  · 技术社区  · 6 年前

    null S2 打印有 writeln ?

    $ dmd -de -w so_004.d && ./so_004
    S1("A", 1)
    S2("A", 1, null)
    

    如果我定义 S2级 在包范围内(即外部 main 消失了。

    采用合理的最新DMD编制:

    $ dmd --version
    DMD64 D Compiler v2.083.0
    Copyright (C) 1999-2018 by The D Language Foundation, All Rights Reserved written by Walter Bright
    

    我在学习的时候注意到了这个问题 opEquals 我不打算在“实”代码的子作用域中定义类型。

    import std.stdio;
    
    void main() {
      {
        struct S1 { string id; ushort x; }
        auto a = S1("A", 1);
        assert(a == a);
        writeln(a);
      }
    
      {
        struct S2 {
          string id; ushort x;
          bool opEquals()(auto ref const string rhs) const {
            return id == rhs;
          }
        }
    
        auto a = S2("A", 1);
        assert(a == "A");
        writeln(a);
      }
    }
    
    0 回复  |  直到 6 年前
        1
  •  1
  •   BioTronic    6 年前

    它是上下文指针(称为 this 在里面 S2.tupleof ),指的是 S2 实例已创建。这通常用于以下代码:

    auto fun(int n) {
        struct S {
            int get() { return n; }
        }
        return S();
    }
    

    上面的代码将分配 n S 成员。

    现在,至于为什么它在你的代码里- that's a bug . 不需要上下文指针,因为结构不使用其作用域中的任何变量。要删除它,只需标记 S2级 static :

    static struct S2 {
        string id; ushort x;
        bool opEquals()(auto ref const string rhs) const {
            return id == rhs;
        }
    }
    
    auto a = S2("A", 1);
    writeln(a); // S2("A", 1)