如何解决 "W1047 Unsafe code '^ operator'" 警告消息?

How to resolve "W1047 Unsafe code '^ operator'" warning message?

我已经启用 "Unsafe code" 警告,我想知道如何解决以下警告:

W1047 Unsafe code '^ operator'

此外,为什么这被认为是"Unsafe code"?

这些警告仅针对 .NET 兼容性(以及用词不当恕我直言)。禁用并忘记它们。

documentation 说:

You have used a data type or operation for which static code analysis cannot prove that it does not overwrite memory. Such code can be considered a security risk.

For example, using GetMem can elicit this warning because a block of memory has no associated type.

实际上只有两种方法可以避免这些警告:

  1. 禁用警告。
  2. 更改代码以停止使用不安全的内存访问。

这两个选项在某些情况下可能都有用。例如,考虑支持动态数组的 Embarcadero Delphi RTL 代码。它需要能够分配内存,并使用此类不安全操作访问该内存。这样的基础库代码需要能够使用不安全的操作。考虑到您自己的代码,如果您需要执行不安全的代码,您可以将其隔离到一个单元或一个单元的单个部分中,并仅针对该代码禁用警告。

关于第二项。您很可能会将使用指针的代码替换为使用其他构造的代码。例如,您可能有使用指针算法的代码,而这些代码可以使用数组来编写。

我认为这些警告是 introduced to help developers migrate code to the long since abandoned Delphi .net compiler。因此,您可能会认为,既然您不以 .net 为目标,那么您可以简单地禁用这些警告。另一方面,我可以看到启用警告并提醒注意潜在风险更高的代码区域可能有用的场景。选择权在你。