关于C++的零散知识点

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++允许在类中包含结构、类和枚举定义。这些嵌套类型的作用域为整个类,这意味着它们被局限于类中,不会与其他地方定义的同名结构、类和枚举发生冲突。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值