为const输入参数传递非常量对象

passing non-const object for const input parameter?

本文关键字:常量 对象 非常 参数传递 const 输入      更新时间:2023-10-16

目前我正在分析以下代码片段:

fvc::surfaceSum(mag(phi))().internalField() 

带有

template<class Type>
tmp<GeometricField<Type, fvPatchField, volMesh> > surfaceSum
(
    const tmp<GeometricField<Type, fvsPatchField, surfaceMesh> >& tssf
)
{
    tmp<GeometricField<Type, fvPatchField, volMesh> > tvf = surfaceSum(tssf());
    tssf.clear();  //If object pointer points to valid object:delete object and 
                           //set pointer to NULL
    return tvf;
}

template<class Type, template<class> class PatchField, class GeoMesh>
tmp<GeometricField<scalar, PatchField, GeoMesh> > mag
(
    const GeometricField<Type, PatchField, GeoMesh>& gf
)
{
    tmp<GeometricField<scalar, PatchField, GeoMesh> > tMag
    (
          new GeometricField<scalar, PatchField, GeoMesh>
          (
                IOobject
                (
                      "mag(" + gf.name() + ')',
                      gf.instance(),
                      gf.db(),
                      IOobject::NO_READ,
                      IOobject::NO_WRITE
                ),
                gf.mesh(),
                gf.dimensions()
          )
    );
    mag(tMag(), gf);
    return tMag;
}

template<class T>
inline const T& Foam::tmp<T>::operator()() const       
{
    if (isTmp_) // bool isTmp_//Flag for whether object is a temporary or a constant object
    {
          if (!ptr_)   //mutable T* ptr_;  //- Pointer to temporary object   
          {
                FatalErrorIn("const T& Foam::tmp<T>::operator()() const")
                << "temporary deallocated"
                << abort(FatalError);
          }
          return *ptr_;  
    }
    else
    {
          return ref_; //const T& ref_  //- Const reference to constant object
    }
}

template<class Type, template<class> class PatchField, class GeoMesh>
typename
Foam::GeometricField<Type, PatchField, GeoMesh>::InternalField 
{                                                                                                                         
    this->setUpToDate();  //Set up to date                                                   
    storeOldTimes();    //Store the old-time fields.
    return *this;
}

第二个代码片段中的方法surfaceSum(…)需要const tmp<GeometricField<Type, fvsPatchField, surfaceMesh> >&作为输入参数,但当使用其他方法时,我得到的结果是一个非常常量参数tmp<GeometricField<scalar, PatchField, GeoMesh> > tMag(请参见第三个代码片段)。因此,是否可以为常量传递一个非常量对象输入参数还是我误解了这里的内容?

问候streight

我找不到任何对surfaceSum的调用(一些typedef会大大提高可读性),但是,是的,您可以将一个非常常量对象作为常量输入参数传递。输入上的const只表示"我不会修改您传递的对象"。