Skip to content

一个学习类型擦除接口时发现的奇怪现象 #191

Answered by w568w
TongVan520 asked this question in 新手提问
Discussion options

You must be logged in to vote

感谢回答,不过我还是不太清楚: 在 std.heap.GeneralPurposeAllocator 中, allocator 函数的源码是:

...
这是写在标准库里的代码,那么为什么 vtable 保存一个 _临时对象_的地址 又是安全的呢? 这个同样也在 上的 临时对象 应该也会 随着函数返回被销毁 才对。

这段代码里的匿名对象不是在栈上的,这是因为它的所有成员都是 const 的,故它是 comptime 的。你可以粗略理解为:

const anony_vtable = VTable { // <- 这是 const 的,因为 alloc、resize…… 都是编译期已知的符号
    .alloc = alloc,
    .resize = resize,
    .remap = remap,
    .free = free,
};
// ...
pub fn allocator(self: *Self) Allocator {
    return .{ // <- 这不是静态的,因为 self 的值是动态传入的
        .ptr = self,
        .vtable = &anony_vtable,
    };
}

这种事情的发生是因为:

Local Variables:

When a local variable is const, it means that after initialization, the variable's value will not change. If the initialization…

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@TongVan520
Comment options

@w568w
Comment options

Answer selected by TongVan520
@jiacai2050
Comment options

@zhylmzr
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
4 participants