草庐IT

c++ - 在 C++ 中为零大小的分配返回唯一地址的基本原理是什么?

coder 2023-06-04 原文

在 C++ 中为零大小的分配返回唯一地址的基本原理是什么?

背景:C11 标准中提到了 malloc(7.20.3 内存管理功能):

If the size of the space requested is zero, the behavior is implementation defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.

也就是说,正如我所见,malloc 对于零大小的分配总是成功的,因为你唯一能用零大小分配的指针做的是调用其他一些内存分配函数,如 免费与它:

  • 如果malloc返回NULLfree(NULL)就ok了,可以认为是成功了,
  • 如果它返回一些其他值,那也是成功(因为它不是 NULL),唯一的条件是该值上的 free 也应该起作用。

此外,C11(也是 7.20.3)没有指定从 malloc 返回的地址必须是唯一的,只是它们必须指向不相交的内存区域:

The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated). The lifetime of an allocated object extends from the allocation until the deallocation. Each such allocation shall yield a pointer to an object disjoint from any other object.

所有大小为零的对象都是不相交的 AFAICT,这意味着 malloc 可以为多个零大小分配返回相同的指针(例如 NULL 就可以了) , 或者每次使用不同的指针,或者某些时候使用相同的指针,等等。

然后 C++98 出现了两个原始内存分配函数:

void* operator new(std::size_t size);
void* operator new(std::size_t size, std::align_val_t alignment);

请注意,这些函数只返回原始内存:它们不会创建或初始化任何 AFAICT 类型的任何对象。

你这样称呼他们:

#include <iostream>
#include <new>
int main() {
    void* ptr = operator new(std::size_t{0});
    std::cout << ptr << std::endl;
    operator delete(ptr, std::size_t{0});
    return 0;
}

C++17 标准的 [new.delete.single] 部分解释了它们,但我看到的关键保证在 [basic.stc.dynamic.分配]:

Even if the size of the space requested is zero, the request can fail. If the request succeeds, the value returned shall be a non-null pointer value (7.11) p0 different from any previously returned value p1, unless that value p1 was subsequently passed to an operator delete. Furthermore, for the library allocation functions in 21.6.2.1 and 21.6.2.2, p0 shall represent the address of a block of storage disjoint from the storage for any other object accessible to the caller. The effect of indirecting through a pointer returned as a request for zero size is undefined.38

也就是说,它们必须始终在成功时返回不同的指针。这与 malloc 有点不同。

我的问题是:这种变化背后的基本原理是什么?(也就是说,在 C++ 中为零大小的分配返回唯一地址的背后)

理想情况下,答案只是指向探索替代方案并激发其语义的论文(或其他来源)的链接。通常我会为这些 C++98 问题选择 The Design and Evolution of C++,但第 10 节(内存管理)没有提及任何相关内容。否则,某种权威的引用会很好。


免责声明:我 asked it on reddit但我问得不够好,所以我没有得到任何有用的答案。我想请问您,如果您只有一个假设,请随时将其作为答案发布,但请提及这只是一个假设。

此外,在 reddit 上,人们继续讨论零大小的类型,我是否有更改标准的建议等。这个问题是关于在传递大小等于零时原始内存分配函数的语义。如果诸如零大小类型之类的主题与您的答案相关,请包括它们!但请尽量不要因切线问题而出轨。

此外,在 reddit 上,人们还提出了诸如“这是出于优化目的”之类的论点,但实际上无法提及更具体的内容。我希望答案中的“因为优化”更具体。例如,一位 redditor 提到了别名优化,但我想知道哪种别名优化适用于无法取消引用的指针,并且无法让任何人对此发表评论。因此,如果您要提及优化,也许可以举一个小例子来丰富讨论。

最佳答案

问题在于 C++ 中的对象(无论其大小)必须具有唯一标识。所以不同的共存对象(不管它们的大小)必须有不同的地址,因为两个比较相等的指针被假定指向同一个对象

如果你承认零大小的对象可以有相同的地址,你就不能再区分两个地址是否是同一个对象。


许多关于“new 不返回对象”问题的评论。

请在此上下文中忘记 OOP 术语:

C++ 规范对“对象”一词的含义有一个精确的定义。

CPP Reference:Object

特别是:

C++ programs create, destroy, refer to, access, and manipulate objects. An object, in C++, is a region of storage that has

  • size (can be determined with sizeof);
  • alignment requirement (can be determined with alignof);
  • storage duration (automatic, static, dynamic, thread-local);
  • lifetime (bounded by storage duration or temporary);
  • type;
  • value (which may be indeterminate, e.g. for default-initialized non-class types);
  • optionally, a name.

The following entities are not objects: value, reference, function, enumerator, type, non-static class member, bit-field, template, class or function template specialization, namespace, parameter pack, and this.

A variable is an object or a reference that is not a non-static data member, that is introduced by a declaration.

Objects are created by definitions, new-expressions, throw-expressions, when changing the active member of a union, and where temporary objects are required.

关于c++ - 在 C++ 中为零大小的分配返回唯一地址的基本原理是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50610274/

有关c++ - 在 C++ 中为零大小的分配返回唯一地址的基本原理是什么?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  3. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  4. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  5. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  6. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  7. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  8. Ruby Koans about_array_assignment - 非平行与平行分配歧视 - 2

    通过ruby​​koans.com,我在about_array_assignment.rb中遇到了这两段代码你怎么知道第一个是非并行赋值,第二个是一个变量的并行赋值?在我看来,除了命名差异之外,代码几乎完全相同。4deftest_non_parallel_assignment5names=["John","Smith"]6assert_equal["John","Smith"],names7end45deftest_parallel_assignment_with_one_variable46first_name,=["John","Smith"]47assert_equal'John

  9. ruby - ruby 中的 TOPLEVEL_BINDING 是什么? - 2

    它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput

  10. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

随机推荐