gpt4 book ai didi

c++ - C++中 'new'运算符什么时候调用构造函数

转载 作者:行者123 更新时间:2023-11-30 04:13:14 25 4
gpt4 key购买 nike

自从我开始学习 C++ 以来,我一直读到“new”运算符在返回指向已分配内存的指针之前调用对象的构造函数。

因此,出于好奇,我检查了"new"的源代码,并在 http://gcc.gnu.org/viewcvs/gcc/trunk/libstdc%2B%2B-v3/libsupc%2B%2B/new_op.cc?revision=197380&view=markup 找到了以下内容

_GLIBCXX_WEAK_DEFINITION void *
operator new (std::size_t sz) _GLIBCXX_THROW (std::bad_alloc)
{
void *p;

/* malloc (0) is unpredictable; avoid it. */
if (sz == 0)
sz = 1;
p = (void *) malloc (sz);
while (p == 0)
{
new_handler handler = std::get_new_handler ();
if (! handler)
_GLIBCXX_THROW_OR_ABORT(bad_alloc());
handler ();
p = (void *) malloc (sz);
}

return p;
}

我没有看到任何构造函数被调用或任何类型的机制来识别对象的类型。

那么,这是怎么做到的呢?编译器是否通过在分配的内存上调用构造函数来耍花招?任何帮助将不胜感激。

此外,对于 new[](在下面的链接中),不会创建任何条目来跟踪数组中的元素数量。那么,delete[] 是如何知道要销毁多少个元素的呢?

http://gcc.gnu.org/viewcvs/gcc/trunk/libstdc%2B%2B-v3/libsupc%2B%2B/new_opv.cc?revision=195701&view=markup

我浏览了很多关于 SO 的相关问题,也用 google 搜索了它,但找不到答案。

最佳答案

I do not see any constructor being called or any sort of mechanism to identify the type of object.

operator new 函数的工作只是分配内存;它不调用构造函数,甚至不知道将在内存中构造什么类型的对象(如果有的话)。它只是告诉要分配多少字节。

Does the compiler play some trick by calling the constructor on the allocated memory?

如果“玩一些把戏”是指“生成一些代码”,那么是的。如果您使用 new 表达式创建一个对象,那么它会做两件事:

  • 调用operator new()为对象分配足够的内存;
  • 调用构造函数来初始化该内存中的对象。

Also, in case of new[] (at link below), no entry is being made to keep track of the number of elements in the array. So, how does delete[] know how many elements to be destructed?

new[] 表达式(不是operator new[])将把它记录在某处。具体细节留给实现。

关于c++ - C++中 'new'运算符什么时候调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19472418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com