gpt4 book ai didi

pointers - Julia-Lang 匿名与命名函数在传递参数中的行为

转载 作者:行者123 更新时间:2023-12-04 12:57:40 25 4
gpt4 key购买 nike

请参阅 Julia 文档:

In Julia, all arguments to functions are passed by reference.



当我从匿名函数中获取 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

正如@Gnimuc 提到的,Julia-Lang Doc 的另一段解释了 参数传递行为

Julia function arguments follow a convention sometimes called “pass-by-sharing”, which means that values are not copied when they are passed to functions. Function arguments themselves act as new variable bindings (new locations that can refer to values), but the values they refer to are identical to the passed values.



这种“通过分享”的行为和上面的代码有什么关系吗?

最佳答案

来自 pointer_from_objref(object_instance) 的 Julia 文档函数我们得到这个描述:

Get the memory address of a Julia object as a Ptr. The existence of the resulting Ptr will not protect the object from garbage collection, so you must ensure that the object remains referenced for the whole time that the Ptr will be used.



检查以下测试:
x=10
y=10
println(pointer_from_objref(x)) # => Ptr{Void} @0x039ee2c0
println(pointer_from_objref(y)) # => Ptr{Void} @0x039ee2c0

正如我们所见 pointer_from_objref无法返回不可变对象(immutable对象)的 native 地址,这是因为该对象是按值传递的,所以我认为上述问题的答案是 pointer_from_objref在那里被滥用。

关于pointers - Julia-Lang 匿名与命名函数在传递参数中的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32931006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com