英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论