// placenew.cpp -- new, placement new, no delete
#include <iostream>
#include <string>
#include <new>
using namespace std;
const int BUF = 512;
class JustTesting
{
private:
string words;
int number;
public:
JustTesting(const string &s = "Just Testing", int n = 0)
{
words = s; number = n; cout << words << " constructed\n";
}
~JustTesting() { cout << words << " destroyed\n"; }
void Show() const { cout << words << ", " << number << endl; }
};
int main(void)
{
char *buffer = new char [BUF]; // get a block of memory
JustTesting *pc1, *pc2;
pc1 = new (buffer)JustTesting; // place object in buffer
pc2 = new JustTesting("heap1", 20); // place object on heap
cout << "Memory block address:\n" << "buffer: "
<< (void *)buffer << " heap: " << pc2 << endl;
cout << "Memory contents: \n";
cout << pc1 << ": ";
pc1->Show();
cout << pc2 << ": ";
pc2->Show();
JustTesting *pc3, *pc4;
pc3 = new (buffer) JustTesting("bad Idea", 6);
pc4 = new JustTesting("Heap2", 10);
cout << "Memory contents: \n";
cout << pc3 << ": ";
pc3->Show();
cout << pc4 << ": ";
pc4->Show();
delete pc2; // free heap1
delete pc4; // free heap2
delete [] buffer; // free buffer
cout << "Done\n";
return 0;
}
[root@localhost 桌面]# ./new Just Testing constructed heap1 constructed Memory block address: buffer: 0x936a008 heap: 0x936a248 Memory contents: 0x936a008: Just Testing, 0 0x936a248: heap1, 20 bad Idea constructed Heap2 constructed Memory contents: 0x936a008: bad Idea, 6 0x936a290: Heap2, 10 heap1 destroyed Heap2 destroyed Done
pc1 = new (buffer) JustTesting;
pc3 = new (buffer + sizeof(JustTesting)) JustTesting("Better Idea", 6);
int main(void)
{
char *buffer = new char[BUF]; // get a block of memory
JustTesting *pc1, *pc2;
pc1 = new (buffer) JustTesting; // place object in buffer
pc2 = new JustTesting("Heap1", 20); // place object on heap
cout << "Memory block addresses: /n" << "buffer: "
<< (void *)buffer << " heap: " << pc2 << endl;
cout << "Memory contents: ";
cout << pc1 << ": ";
pc1->Show();
cout << pc2 << ": ";
pc2->Show();
JustTesting *pc3, *pc4;
// fix placement new location
pc3 = new (buffer + sizeof(JustTesting)) JustTesting("better Idea", 6);
pc4 = new JustTesting("Heap2", 10);
cout << "Memory contents: ";
cout << pc3 << ": ";
pc3->Show();
cout << pc4 << ": ";
pc4->Show();
delete pc2; // free heap1
delete pc4; // free heap2
// explicitly destroy placement new object
pc3->~JustTesting(); // destroy object pointed to by pc3
pc1->~JustTesting(); // destroy object pointed to by pc1
delete []buffer; // free buffer
cout << "Done/n";
return 0;
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有