前言
今天看到一个程序,用到了智能指针,
virtual tmp<volScalarField> rho() const;
借此机会把有关智能指针的知识体系重新梳理一遍
智能指针autoPtr的由来:
首先要说明智能指针本质上是模板类,是对原有指针的改进,相比更安全,
of对autoPtr的描述如下:
An auto-pointer similar to the STL auto_ptr but with automatic casting
to a reference to the type and with pointer allocation checking on access.
of中的智能指针autoPtr很像原有的auto_ptr,但不是对原有的封装,而是重新写了一遍
再看std::auto_ptr
std::auto_ptr的定义大致如下:
template <typename _Tp>
class auto_ptr
{
private:
_Tp *_M_ptr;
public:
explicit auto_ptr(_Tp *__p = 0) throw();
auto_ptr(auto_ptr &__a) throw();
auto_ptr &operator=(auto_ptr &__a) throw();
~auto_ptr();
_Tp &operator*() const throw();
_Tp *operator->() const throw();
_Tp *get() const throw();
_Tp *release() throw();
void reset(_Tp *__p = 0) throw();
};
再看咱of中的autoPtr是何其相似,
template<class T>
class autoPtr
{
mutable T* ptr_;
public:
typedef T Type;
inline explicit autoPtr(T* = nullptr);
inline autoPtr(const autoPtr<T>&);
inline autoPtr(const autoPtr<T>&, const bool reuse);
inline ~autoPtr();
inline bool empty() const;
inline bool valid() const;
inline T* ptr();
inline void set(T*);
inline void reset(T* = nullptr);
inline void clear();
inline T& operator()();
inline const T& operator()() const;
inline T& operator*();
inline const T& operator*() const;
inline operator const T&() const;
inline T* operator->();
inline const T* operator->() const;
inline void operator=(T*);
inline void operator=(const autoPtr<T>&);
};
在autoPtr中,我们也能看到在autoPtr中加了很多unique_ptr的元素,比如说reset(),
那为什么要用智能指针呢,他的应用场景是哪些,下次我们自己写的时候要什么时候用
为什么要用智能指针:
举个例子,比如说我们要实现插值算法,用matlab写,这很简单
result = function(input)
现在我们学习C++了,知道了可以传指针或引用,可以这样写
function(&result, input);
相比之下of更倾向于使用matlab的书写方式
因为简单
不仅是看起来简单,写起来也简单,可以更直观的表达想法
对于没接触过C或C++的人来说,不必了解引用左值右值等一系列知识
在of中写动量方程,
fvVectorMatrix UEqn
(
fvm::ddt(rho, U)
+ fvm::div(rhoPhi, U)
+ turbulence->divDevRhoReff(rho, U)
);
首先这是个类fvVectorMatrix的构造函数,还是个拷贝构造
那这就需要括号内操作符重载以及函数返回类型都是fvVectorMatrix类
对于需要引入方程的人来说显式写法更直观更简单,如果写成function(&result, input)这样,一个两个还好,方程多了会非常乱
但是C++作为效率最高的语言,引用这个概念的提出肯定有他的道理
引用是什么,很多说是别名
实际上引用的本质是指针常量,如果换C语言的写法是这样的
int* const rb = &a;
matlab以简单易用著称,但用过matlab的人都知道matlab的效率极低,
本科时候当时不会向量化编程,参加数学建模比赛跑一个循环,跑了整整24小时,笔记本散热也不大行,后来送修主板了
为什么matlab效率低,很关键的一点是matlab一直都是复制拷贝
C/C++指针传地址效率就高很多,况且C++引用的本质就是指针,只不过是const修饰地址的指针
在简单易用和效率之间,matlab选择了前者,C++选择了后者
openfoam是一个非常强大的张量计算程序,既不能舍弃易用性抬高门槛,又不能反复使用复制拷贝降低效率,稀疏矩阵那么大拷贝来拷贝去算一个程序跑好几年成本太高
openfoam使用智能指针解决了这个问题,看起来不难读懂又能保证效率
这也就回答了为什么要使用智能指针
再回到我们刚刚说的动量方程拷贝构造上,首先在书写方法上依旧是matlab的显式书写方法,但实际上是C++的隐式移动拷贝
在哪里看到用指针了,可以打开fvm命名空间的内容
namespace fvm
{
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
template<class Type>
tmp<fvMatrix<Type>>
d2dt2
(
const GeometricField<Type, fvPatchField, volMesh>& vf
)
{
return fv::d2dt2Scheme<Type>::New
(
vf.mesh(),
vf.mesh().d2dt2Scheme("d2dt2(" + vf.name() + ')')
).ref().fvmD2dt2(vf);//这里返回的可是fvMatrix<Type>类型指针哦
}
template<class Type>
tmp<fvMatrix<Type>>
d2dt2
(
const dimensionedScalar& rho,
const GeometricField<Type, fvPatchField, volMesh>& vf
)
{
ret