1. ostream类没有公有的复制构造函数。
2. 使用定位new运算符的注意事项
delete[] buffer,释放使用常规new运算符分配的整个内存块,但它没有为定位new运算符在该内存块中创建的对象调用析构函数。注意以下代码示例,注意如果使用定位new运算符(而不是常规new运算符)为对象分配内存,并将其地址赋给一个指针,则必须负责显式地为该对象调用析构函数,方法是使用指向该对象地指针调用析构函数。
#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()
{
char* buffer = new char[BUF];
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:\n" << 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:\n";
cout << pc3 << ": ";
pc3->Show();
cout << pc4 << ": ";
pc4->Show();
delete pc2; //free Heap1
delete pc4; //free Heap2
//!!!! explicitly destroy placement new objects
pc3->~JustTesting(); //destroy object pointed to by pc3
pc4->~JustTesting();
delete [] buffer; //free buffer
cout << "Done\n";
return 0;
}
3. C++允许在类中包含结构、类和枚举定义。这些嵌套类型的作用域为整个类,这意味着它们被局限于类中,不会与其他地方定义的同名结构、类和枚举发生冲突。