需要动态分配一个单独的整数吗?

huangapple go评论86阅读模式
英文:

Is there ever a need to allocate a single int dynamically?

问题

Here's the translation of the provided text:

"动态分配的一个示例在cppreference.com上是:

int* p1 = new int;

是否有必要动态分配一个单独的int?

英文:

One example of dynamic allocation on cppreference.com is:

int* p1 = new int;

Is there ever a need to allocate a single int dynamically?

答案1

得分: 1

当你的应用逻辑中所有整数值都有效时,使用 int* 添加了额外的 NULL 值。这在例如处理可为NULL的 int 类型数据库列时非常有用。

另外,在16位系统上,int 操作不是原子性的,因此在从另一个线程读取时更新 int 值不是线程安全的操作,但共享一个 int* 是线程安全的。

(是的,我在这里有些牵强,但我过去曾经都用过这两种方法)

英文:

When all integral values are valid in your application's logic, using an int* adds the additional NULL value. This is useful when, for example, you are dealing with a NULLABLE database column of type int.

Additionally, on 16-bit systems, int operations weren't atomic, so updating an int value while reading it from another thread isn't a threadsafe operation, but sharing an int* is.

(Yeah, I'm stretching here, but I have used both in the past)

huangapple
  • 本文由 发表于 2020年1月7日 00:04:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615265.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定