C++ Boost库:简介和第一个示例程序
C++ Boost库:数值转换 lexical_cast
C++ Boost库:字符串格式化 format
C++ Boost库:字符串string_algo
C++ Boost库:字符串算法string_algo
C++ Boost库:类型推导BOOST_AUTO/BOOST_TYPEOF
C++ Boost库:分词处理库 tokenizer
C++ Boost库:windows下编译Boost库
C++ Boost库:日期时间库 date_time
C++ Boost库:智能指针scoped_ptr
C++ Boost库:数组智能指针 scoped_array
C++ Boost库:共享所有权的智能指针 shared_ptr
C++ Boost库:工厂函数 make_shared
C++ Boost库:共享有权的数组智能指针shared_array
C++ Boost库:弱引用智能指针 weak_ptr
C++ Boost库:禁止拷贝 nocopyable
C++ Boost库:计时器 timer
C++ Boost库:普通数组array
C++ Boost库:散列容器 unordered_set、unordered_multiset
C++ Boost库:散列容器 unordered_map、unordered_multimap
C++ Boost库:双向映射容器 bimap
C++ Boost库:环形缓冲区 circular_buffer
C++ Boost库:动态多维数组 multi_array
C++ Boost库:使用property_tree解析XML和JSON
C++ Boost库:简化循环 BOOST_FOREACH
C++ Boost库:随机数库 Random
C++ Boost库:引用库 ref
C++ Boost库:绑定库 bind
C++ Boost库:线程库 thread 跨平台多线程
C++ Boost库:互斥量 mutex
1. 如何消除new
shared_ptr消除了显式的 delete调用,很大程度上避免了程序员忘记 delete而导致的内存泄漏。但 shared_ptr的构造依然需要ηew,这导致了代码中的某种不对称性,它应该使用工厂模式来解决。
2. 工厂函数
Boost库提供了一个自由工厂函数 make shared<T>(),来消除显式的new调用,声明如下:
template<class T,class... Args>
shared_ptr<T> make_shared(Args && ... args);
make_shared()函数模板使用变长参数模板,最多可接受10个参数然后把它们传递给T的构造函数,创建一个 shared_ptr<T>的对象并返回。make_shared()函数要比直接创建 shared_ptr对象的方式更高效,因为它內部仅分配一次內存。使用时需要包含头文件:
#include<boost/make_shared.hpp>
3. 示例代码
#include<iostream>
using namespace std;
#include<boost/make_shared.hpp>
using namespace boost;
class A
{
public:
A(int _a ,float _b, char _c ,string _d)
{
a=_a ; b = _b; c = _c; d = _d;
cout << "构造A类对象!" << endl;
}
~A( )
{
cout << "析构A类对象!" << endl;
}
int a;
float b;
char c;
string d;
};
int main()
{
//原始的方式构造shared_ptr,需要new,产生一种不对称性
boost::shared_ptr<A> p1(new A(100, 1.234f, 'C', "hello"));
cout << p1->a << ", " << p1->b << ", " << p1->c<< ", " << p1->d << endl;
//推荐使用工厂函数,屏蔽new ,更高效
boost::shared_ptr<A> p2 = boost::make_shared<A>(100, 1.234f, 'C', "hello");
cout << p2->a << ", " << p2->b << ", " << p2->c << ", " << p2->d << endl;
getchar();
return 0;
}
运行结果:

本文介绍了C++ Boost库中智能指针的作用,特别是`shared_ptr`如何通过工厂函数`make_shared`消除显式的`new`操作,提高效率并减少内存泄漏的风险。通过示例代码展示了`make_shared`的使用方法,强调了其在构建对象时的一次内存分配优势。
6251

被折叠的 条评论
为什么被折叠?



