为什么在Linux64下使用.ptr修补字符串失败但在Win32下没有?

bab*_*u67 3 string portability pointers d

为什么下面的小样本在Linux64下失败但在Windows32下失败?

module test;

import std.string, std.stdio;

void main(string[] args)
{
    string a = "abcd=1234";
    auto b = &a;
    auto Index = indexOf(*b, '=');

    if (Index != -1)
        *cast (char*) (b.ptr + Index) = '#';

    writeln(*b);
    readln;
}
Run Code Online (Sandbox Code Playgroud)

rat*_*eak 6

要记住的一件事是,这string是一个别名,(immutable char)[]这意味着尝试写入元素是未定义的行为

我认为行为不同的原因之一是在linux64下编译器将字符串数据放入写保护的内存中,这意味着*cast (char*) (b.ptr + Index) = '#';失败(无论是静默还是使用segfault)

  • 它只是意味着win不为代码提供只读内存块(通常存储字符串文字) (3认同)
  • 没有"绝对的不变性".不可变只是D中的编译时类型注释,如果忽略编译时间检查,则无法知道运行时会发生什么.string.ptr返回immutable(char)*,并且编译器在编译时保证您不能修改此指针指向的数据.如果你转换为char*那么它绝对未定义在运行时会发生什么.虽然语言可以提供额外的运行时检查,但D不是出于性能原因.linux上的segfault只是我们免费获得的特定于Linux的安全网. (3认同)