std::unique_ptr简单用法

 使用指针的一个好处,就是它代表了一定的状态,比如如果无效,那就是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 个参数

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值