使用指针的一个好处,就是它代表了一定的状态,比如如果无效,那就是NULL。有效的时候才有值。不用再定义一个它状态变量来记录数据是否有效。定义状态变量就牵扯到一致性的问题,增加出错几率。
struct Position
{
Position(float x, float y) : x(x), y(y)
{
std::cout << "Position(float x, float y)" << std::endl;
}
Position()
{
std::cout << "Position()" << std::endl;
}
~Position()
{
std::cout << "~Position()" << std::endl;
}
float x;
float y;
};
reset和move的正确用法。间接使用了release
{
std::unique_ptr<Position> pos = std::make_unique<Position>(1.0f,2.0f);
pos.reset(std::make_unique<Position>(4.0f, 5.0f).release());
//std::vector<int> v;
//v.pop_back();
int i = 0;
++i;
pos = std::move(std::make_unique<Position>(7.0f, 8.0f));
int j = 0;
++j;
return i;
}
在类里面初始化,可以这样
struct XXX
{
std::unique_ptr<double> floorElevation {std::make_unique<double>(0.0)};
};
如果类没有对应的构造函数,那么会出现
struct GEOMDLLIMPEXP DPoint3d
{
//! x coordinate
double x;
//! y coordinate
double y;
//! z coordinate
double z;
#ifdef __cplusplus
//BEGIN_FROM_METHODS
//! Return a DPoint3d with given xyz.
static DPoint3d From (double x, double y, double z = 0.0);
//! Return a DPoint3d with given xy, z = 0;
static DPoint3d From (DPoint2dCR xy);
//! Return a DPoint3d with xyz = 0.
static DPoint3d FromZero();
//! Return a DPoint3d with xyz = 1.
static DPoint3d FromOne();
static DPoint3d FromXYZ (double x, double y, double z);
//! @description Simple initialization from 3 coordinates in array.
//! @param [in] pXyz x, y, z components
static DPoint3d FromArray (const double *pXyz);
//END_FROM_METHODS
//! Swap contents of instance, other.
//! @param [in,out] other second point.
void Swap (DPoint3dR other);
...
};
void fun()
{
std::unique_ptr<DPoint3d> intersectPt = std::make_unique<DPoint3d>(0.0, 0.0, 0.0);
}
编译错误:
c:\DevTools\VS2017\VC\Tools\MSVC\14.16.27023\include\memory(2539): error C2661: “Bentley::DPoint3d::DPoint3d”: 没有重载函数接受 2 个参数
...\FindWellByPipeUtil.cpp(926): note: 参见对正在编译的函数 模板 实例化“std::unique_ptr<Bentley::DPoint3d,std::default_delete<_Ty>> std::make_unique<Bentley::DPoint3d,double,double,0>(double &&,double &&)”的引用
with
[
_Ty=Bentley::DPoint3d
]
当然,直接 new DPoint3d(0,0,0)也会提示:
error C2661: “Bentley::DPoint3d::DPoint3d”: 没有重载函数接受 3 个参数