c++ 传递参数

模板传递参数获取大小

点击查看代码
template <class Ty, size_t Size>
void TestMem(Ty(&data)[Size])
{
	cout << "size of data =" << sizeof(data) << endl;
}
int main(int argc, char* argv[])
{
	char data[] = "test memory ptr";
	TestMem(data);
	return 0;
}

string 传参

点击查看代码
void TestStr(string &in_data)
{
	cout << "data:" << in_data << endl;
	cout << "data addr:" << reinterpret_cast<long long>(in_data.data()) << endl;
}

int main(int argc, char* argv[])
{
	string str1;
	str1.resize(1024);
	auto data = const_cast<char*>(str1.data());
	memset(data,'A', 5);

	cout <<"str1"<< str1 << endl;
	cout << "str1 addr:" << reinterpret_cast<long long>(data) << endl;
	TestStr(str1);
	return 0;
}

重载new,delete

  • 监测内存
  • 内存对齐
点击查看代码
class Test1
{
public:
	Test1()
	{
		cout << "create Test1" << endl;
	}
	~Test1()
	{
		cout << "clear Test1" << endl;
	}

	void* operator new(size_t size)
	{
		cout << "class new:" << size << endl;
		auto mem = malloc(size);
		if (!mem)
		{
			throw std::bad_alloc();
		}
		return mem;
	}
	void* operator new[](size_t size)
	{
		cout << "class new arry:" << size << endl;
		auto mem = malloc(size);
		if (!mem)
		{
			throw std::bad_alloc();
		}
		return mem;
	}

	void operator delete(void* ptr)
	{
		cout << "class delete" << endl;
		std::free(ptr);
	}

	void operator delete [](void* ptr)
	{
		cout << "class arry delete" << endl;
		std::free(ptr);
	}


	void* operator new(size_t size, void* ptr)
	{
		cout << "placement new" << endl;
		return ptr;
	}

	int index = 0;
};

placement new生成对象可以在堆上和栈上。

点击查看代码
int buf[1024] = { 0 };
Test1* mem1 = ::new(buf) Test1;

int* buf2 = new int[1024]{ 0 };
auto mem2 = ::new(buf2) Test1;
delete mem2;

int* buf3 = new int[1024]{ 0 };
auto mem4 = new(buf3)Test1;

mem4->~Test1();
delete[] buf3;

allocator存储和实现隔离

点击查看代码
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/*
* 对象内存分配和隔离
*/

class Data
{
public:
	Data()
	{
		cout << "create data" << endl;
	}
	~Data()
	{
		cout << "clear data" << endl;
	}
};

int main(int argc, char* argv[])
{
	allocator<Data> data_alloc;
	int size = 3;
	//不调用构造函数,实际调用new方法
	auto dataArr = data_alloc.allocate(size);
	//不调用析构
	data_alloc.deallocate(dataArr, size);
	/**
	* allocator_traits 类模板提供分配器标准化方式
	* decltype(data_alloc) = allocator<Data>
	*/
	//调用构造
	allocator_traits< decltype(data_alloc)>::construct(data_alloc, &dataArr[1]);
	//析构函数
	allocator_traits< decltype(data_alloc)>::destroy(data_alloc, &dataArr[1]);


	return 0;
}
posted @ 2026-02-13 16:52  fangshuo  阅读(2)  评论(0)    收藏  举报