【发布时间】:2018-11-28 18:20:01
【问题描述】:
我写了以下代码来理解运算符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 类中重写的运算符新称为 size_t n = 8 Sizeof(Dog) = 8
全局运算符新调用 - 请求:8,在:0xf15c20
狗构造
狗构造
===========================================
知道为什么 Dog 对象 Dog 的构造函数会被调用两次吗?
谢谢
【问题讨论】:
标签: c++