In C ++, we often encounter three kinds of new forms: operator new, new operator, placement new
Operator ①new (new new operator) : ① ② space applications create objects
Illustrates the steps of:
②operator new (operator new new) : Application Space
③placement new (locating new new) : create an object in space has applied
Format: new (ptr) A ( "123") ptr --- application point has a good spatial
Summary: ②③ is considered to be a simple operation ① Netvibes. However ②③, when the need to release the space, need to explicitly call spatial object class destructor release entity member applications.
Application Code:
#include<iostream> using namespace std; //operator new //new operator //placement new //重载new operator void* operator new(size_t sz) { void* p = malloc(sz); return p; } void operator delete(void *p) { free(p); } void operator delete[](void *p) { free(p); } class String; ostream& operator<<(ostream& out, String& str); class String { public: friend ostream& operator<<(ostream& out, String& str); public: String(const char* str = "") { std::cout<<"contruct Object"<<std::endl; if (str == NULL) { m_data = new char[1]; m_data[0] = '\0'; } else { m_data = new char[strlen(str) + 1]; strcpy(m_data,str); } } ~String() { cout<<"free Object"<<endl; delete[]m_data; m_data = NULL; } private: char* m_data; }; ostream& operator<<(ostream& out, String& str) { out << str.m_data; return out; } int main() { String *str = new String("Hello");// new operator delete str; String *str = new String[10]; String *ps = (String *)operator new(sizeof(String)); //operator new new(ps)String("Hello"); //placement new ps->~String(); operator delete(ps); return 0; }