[英]C++ class constructor is called twice when new operator is overriden - why
我编写了以下代码来解释运算符new
#include <iostream>
using namespace std;
class Dog {
public:
Dog() {
cout << "Dog constructed\n";
}
//overriding the new operator of the class and explicitely doing what it internally does
void* operator new(size_t n) {
cout << "operator new overriden in Dog class called size_t n = " << n << " Sizeof(Dog) = "<< sizeof(Dog) << endl;
//Allocating the memory by calling the global operator new
void* storage = ::operator new (n);
// you can now create the Dog object at the allcated memory at the allocated memory
::new (storage) Dog(); //---------> Option 1 to construct the Dog object --> This says create the Dog at the address storage by calling the constructor Dog()
return storage;
}
int m_Age = 5;
int m_Color = 1;
};
void* operator new(std::size_t size)
{
void* storage = malloc(size);
std::cout << "Global operator new called - Asked for: " << size
<< ", at: " << storage << std::endl;
return storage;
}
int main(int argc, char** argv)
{
cout << "calling new Dog" << endl;
Dog* ptr = new Dog;
int x;
cin >> x;
return 0;
}
当我运行它时,输出如下
================================================
叫新狗
Dog类中的operator new overriden,名为size_t n = 8 Sizeof(Dog)= 8
全局运营商新召集 - 要求:8,at:0xf15c20
狗构造
狗构造
==========================================
任何想法为什么Dog对象Dog的construcor被调用两次?
谢谢
它是因为你在重载operator new中使用placement new构造一个Dog
对象,同时为正在构造的Dog object
分配存储:
::new (storage) Dog();
operator new永远不应该构造一个对象,它应该只分配内存,编译器将使用分配的内存发出代码来构造一个对象。
这是因为你要构建Dog
在这只能在一定的分配空间功能Dog
。 然后编译器在那个上构造第二个Dog
。
观察返回类型是void*
,即指向unknown的指针。 如果您打算构建一只Dog
,返回值将是Dog*
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.