请参阅Julia doc:
在Julia中,函数的所有参数都通过引用传递.
当我从匿名函数中获取Float64参数的内存地址时,它看起来是正确的.但对于命名函数来说并非如此.
test = function (a::Float64)
println(pointer_from_objref(a));
end
# => (anonymous function)
function test1(a::Float64)
println(pointer_from_objref(a));
end
# => test1 (generic function with 1 method)
value=0.0;
println(pointer_from_objref(value))
# => Ptr{Void} @0x00007fe797c5c020
test(value)
# => Ptr{Void} @0x00007fe797c5c020
test1(value)
# => Ptr{Void} @0x00007fe799e83960
Run Code Online (Sandbox Code Playgroud)
正如@Gnimuc所提到的,Julia-Lang Doc还有另一段解释了Argument Passing Behavior
Julia函数参数遵循有时称为"pass-by-sharing"的约定,这意味着值在传递给函数时不会被复制.函数参数本身充当新的变量绑定(可以引用值的新位置),但它们引用的值与传递的值相同.
这种"传递共享"行为与上述代码之间是否存在任何关系?
从 Juliapointer_from_objref(object_instance)
函数文档中我们得到了这样的描述:
获取 Julia 对象的内存地址作为 Ptr。生成的 Ptr 的存在不会保护该对象免遭垃圾回收,因此必须确保该对象在使用 Ptr 的整个过程中保持引用状态。
检查以下测试:
x=10
y=10
println(pointer_from_objref(x)) # => Ptr{Void} @0x039ee2c0
println(pointer_from_objref(y)) # => Ptr{Void} @0x039ee2c0
Run Code Online (Sandbox Code Playgroud)
正如我们所看到的,pointer_from_objref
无法返回不可变对象的本机地址,这是因为该对象是按值传递的,所以我认为上述问题的答案是pointer_from_objref
那里被误用了。
归档时间: |
|
查看次数: |
358 次 |
最近记录: |