e");
return 0;
}
一般在默认情况下object_pool
内存池只能接收三个以内的参数传递,当读者需要使用多于三个参数时则需要使用自定义可变参数模板来实现功能,我们以接受四个参数为例,定义construct
模板并在该模板内部实现分配资源。
#include <iostream>
#include <string>
#include <boost/pool/object_pool.hpp>
using namespace std;
using namespace boost;
struct MyStruct
{
public:
int uuid;
string uname;
int uage;
string usex;
MyStruct(int uuid_, string uname_, int uage_, string usex_)
{
uuid = uuid_; uname = uname_; uage = uage_; usex = usex_;
}
};
// 定义可变参数模板,用来实现接受三个以上的参数
template<typename P, typename ... Args> inline typename P::element_type* construct(P& p, Args&& ... args)
{
typename P::element_type* mem = p.malloc();
new(mem) typename P::element_type(std::forward<Args>(args)...);
return mem;
}
int main(int argc, char const *argv[])
{
boost::object_pool<MyStruct> object;
auto ptr = object.malloc();
// 接收四个参数写法
auto ref = construct(object, 1001, "lyshark", 24, "男");
cout << "姓名: " << ref->uname << endl;
object.free(ref);
object.free(ptr);
std::system("pause");
return 0;
}
2.3 使用SharedPtr智能指针
boost::shared_ptr是Boost
库中的一个智能指针,用于自动管理动态分配的内存。它跟踪有多少个shared_ptr
实例共享同一个对象,当最后一个实例离开作用域时,它会自动释放分配的内存。
该函数是boost.smart_ptr
库中最重要的智能指针,shared_ptr
包装了new
操作符在堆上分配的动态对象,实现了引用计数型的智能指针,可被自由的拷贝和赋值,并在任意地方共享。
#include <iostream>
#include <string>
#include <boost/smart_ptr.hpp>
using namespace std;
using namespace boost;
int main(int argc, char const *argv[])
{
// 基本的定义与赋值
boost::shared_ptr<int> int_ptr(new int);
*int_ptr = 1024;
cout << "指针: " << &int_ptr << " 数值: " << *int_ptr << endl;
boost::shared_ptr<string> string_ptr(new string);
*string_ptr = "hello lyshark";
cout << "指针: " << &string_ptr << " 长度: " << string_ptr->size() << endl;
// 拷贝构造的使用
boost::shared_ptr<int> shared_ptr(new int(10)); // 定义指向整数的shared
cout << "持有者: " << shared_ptr.unique() << endl;
boost::shared_ptr<int>shared_copy = shared_ptr; // 实现拷贝
cout << "引用数: " << shared_ptr.use_count() << endl;
shared_ptr.reset(); // 关闭shared的使用
getchar();
return 0;
}
在有时候我们需要使用多个指针,并将多个指针分别指向不同的数据集合,此时我们可以先封装一个MyShared
类,并使用循环的方式初始化创建内存空间,每次创建空间后将该空间存储至vect
容器内,最后再以此循环输出该容器内存所有自定义类元素即可;
#include <iostream>
#include <vector>
#include <string>
#include <boost/shared_ptr.hpp>
using namespace std;
using namespace boost;
// 定义Shared类
class MyShared
{
private:
int shared_uuid;
std::string shared_name;
public:
MyShared(int x, std::string y)
{
shared_uuid = x;
shared_name = y;
}
std::string GetName()
{
return shared_name;
}
int GetUUID()
{
return shared_uuid;
}
};
int main(int argc, char const *argv[])
{
std::vector<boost::shared_ptr<MyShared>> vect;
// 循环开辟空间,并放入vector列表
for (int x = 0; x < 5; x++)
{
boost::shared_ptr<MyShared> ptr(new MyShared(x,"hello lyshark"));
vect.push_back(ptr);
}
// 输出列表中的元素
for (int x = 0; x < vect.size(); x++)
{
std::cout << "UUID: " << vect[x]->GetUUID() << " Name: &q