简体   繁体   English

Swift中的通用函数参数指向无效的内存

[英]Generic function parameter in Swift points to invalid memory

I'll start with an example setup. 我将从一个示例设置开始。

class Parent {
    let parentProperty = 1
}
class Child : Parent {
    let childProperty = 2
}
class Test {
    func testMethod<T : Parent>(data: T) {
        // (llbd) print data
    }
}

let child = Child()
let test = Test()
// (lldb) print child
test.testMethod(child)

I paused execution on places marked with comment "(lldb) print ..." and executed "print child/data" command in debugger console in Xcode. 我在标有注释“(lldb)print ...”的地方暂停了执行,并在Xcode的调试器控制台中执行了“ print child / data”命令。

Output from said commands are listed below. 所述命令的输出在下面列出。

// print child //打印孩子

(RingRingTests.Child) $R0 = 0x00007fcb886459a0 {
  RingRingTests.Parent = {
    parentProperty = 1
  }
  childProperty = 2
}

// print data //打印数据

(RingRingTests.Child) $R1 = 0x0000000115a93818 {
  RingRingTests.Parent = {
    parentProperty = 140512143366480
  }
  childProperty = 4294967299
}

The child and data variables obviously point to different location in memory. 子变量和数据变量显然指向内存中的不同位置。 (being that data point to some invalid memory) (因为该数据指向一些无效的内存)

This seems to be like the most basic setup for generic function is swift, nevertheless it is failing. 这似乎是通用函数的最基本设置很快,但是失败了。

I guess I'm doing something fundamentally wrong. 我猜我在做一些根本错误的事情。 Can somebody point me to the right direction? 有人可以指出我正确的方向吗? Thank you. 谢谢。

I've tried to replace your proposed lldb-tests with plain old debug output and all works fine. 我试图用简单的旧调试输出替换您建议的lldb-tests,并且一切正常。

class Parent: CustomDebugStringConvertible {
    let parentProperty = 1
    var debugDescription: String { return "\(parentProperty)" }
}
class Child: Parent {
    let childProperty = 2
    override var debugDescription: String { return "\(parentProperty), \(childProperty)" }
}
class Test {
    func testMethod<T : Parent>(data: T) {
        print(data)
    }
}

let child = Child()
let test = Test()
print(child) // 1, 2
test.testMethod(child) // 1, 2

Some optimisation can screw lldb-tests, but optimisation should not be done for debug builds. 某些优化可以使lldb-test陷入困境,但不应对调试版本进行优化。

In other words, my answer is "it's actually all right with your code, but maybe something is wrong with your tests". 换句话说,我的回答是“您的代码实际上没问题,但是您的测试可能有问题”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM