美文网首页
Swift 指针打印

Swift 指针打印

作者: 幸运者_Lucky | 来源:发表于2022-03-04 16:33 被阅读0次

    下面代码测试 Copy on write

    func run() {
        let a = ["asdfdasoifljasodlfjasoldjfkoasldk", "asdfdasoifljasodlfjasoldjfkoasldk", "asdfdasoifljasodlfjasoldjfkoasldk"]
        var b = a
    
        print(String(format: "a: %p, a[0]: %p", a, a[0]))
        print(String(format: "b: %p, b[0]: %p", b, b[0]))
    
        b.append("asdfdasoifljasodlfjasoldjfkoasldk")
        print(String(format: "b: %p, b[0]: %p", b, b[0]))
    }
    
    run()
    
    // print: 
    // a: 0x60000092ee20, a[0]: 0x60000072d2c0
    // b: 0x60000092ec60, b[0]: 0x60000072d410
    // b: 0x60000092ebe0, b[0]: 0x60000072d3b0
    

    值类型因为作为参数传递的时候已经是一个新指针。
    Your code is printing the addresses of the array buffers (Array is a special case when passing a value to a pointer parameter). However, in Swift 3, the compiler assumed that the presence of the & operator meant that the buffer was being passed as mutable memory, so (unnecessarily) made it unique (by copying) before passing its pointer value, despite that pointer value being passed as an UnsafeRawPointer. That's why you see different addresses.
    Referrence

    打印值类型可以通过这种方式打印

    func address(_ p: UnsafeRawPointer) {
        print(p)
    }
    
    func run() {
        let a = ["asdfdasoifljasodlfjasoldjfkoasldk", "asdfdasoifljasodlfjasoldjfkoasldk", "asdfdasoifljasodlfjasoldjfkoasldk"]
        var b = a
    
        address(a)
        address(b)
        
        b.remove(at: 0)
        address(b)
    }
    
    run()
    

    相关文章

      网友评论

          本文标题:Swift 指针打印

          本文链接:https://www.haomeiwen.com/subject/xoxezctx.html