c++关于在自复制判别时 this != & ths 式中的理解

在C++中,this是一个特殊的指针,它在非静态成员函数内部自动声明,指向调用该函数的对象。this本质上是一个指向当前对象的常量指针,类型为const T*,其中T是对象的类型。这意味着你不能通过this修改对象的类型,但可以通过它访问对象的所有非静态成员。

当你看到this != &rhs这样的比较时,实际上是在比较两个对象的地址。这里,this指向调用赋值运算符的左侧对象,而&rhs获取右侧对象的地址。比较这两个地址可以判断是否正在尝试对同一个对象进行赋值,这种情况称为“自赋值”。如果发生自赋值,就不需要执行任何深拷贝操作,因为赋值的目标和源实际上是同一个对象。

考虑以下代码片段:

class MyClass {
public:
    MyClass& operator=(const MyClass& rhs) {
        if (this != &rhs) {
            // 进行深拷贝或其他赋值操作
        }
        return *this;
    }
};

在这段代码中:

  • this指向调用赋值运算符的MyClass实例。
  • &rhs获取传递给赋值运算符的rhs参数的地址,rhs也是一个MyClass实例。
  • 如果this&rhs指向不同的地址,说明我们正在处理两个不同的对象,这时才需要执行深拷贝或其他赋值逻辑。

因此,this在这里被用来识别是否正在进行自赋值,从而避免不必要的资源消耗和潜在的错误。如果确实进行了自赋值,this != &rhs条件不满足,赋值运算符就不会执行深拷贝等操作,而是直接返回*this,即当前对象的引用。这样可以支持链式赋值,例如a = b = c;,并且效率更高,因为不需要做无意义的拷贝工作。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SELECT th.id hotelId, th.hotel_name hotelName, th.country_name countryName, th.city_name cityName, th.active, d.supplyclass as supplyClass, if(ISNULL(a.sort_rank),1000,a.sort_rank) sort FROM t_baseinfo_hotel th LEFT JOIN (SELECT * FROM t_baseinfo_hotel_sort ths WHERE ths.org_code = #{orgCode})a ON a.hotel_id = th.id LEFT JOIN (SELECT hotel_id,GROUP_CONCAT(supplyclass) supplyclass from t_supply_hotel_mapping where 1=1 <if test="hotelId != null and hotelId != ''"> AND hotel_id = #{hotelId} </if> <if test="hotelIds != null and hotelIds != ''"> AND hotel_id IN <foreach item="item" index="index" collection="hotelIds.split(',')" open="(" separator="," close=")"> #{item} </foreach> </if> <if test="supplierCodes != null and supplierCodes != ''"> AND supplyclass IN <foreach item="item" index="index" collection="supplierCodes.split(',')" open="(" separator="," close=")"> #{item} </foreach> </if> GROUP BY hotel_id ) d on th.id =d.hotel_id WHERE th.deleted = 0 <if test="cityCode != null and cityCode != ''"> AND th.city_code = #{cityCode} </if> <if test="hotelId != null and hotelId != ''"> AND th.id = #{hotelId} </if> <if test="null != hotelName and hotelName != ''"> AND th.hotel_name LIKE "%"#{hotelName}"%" </if> <if test="active != null and active == 1"> AND th.active = 1 </if> <if test="hotelIds != null and hotelIds != ''"> AND th.id IN <foreach item="item" index="index" collection="hotelIds.split(',')" open="(" separator="," close=")"> #{item} </foreach> </if> <if test="supplierCodes != null and supplierCodes != ''"> AND th.id =d.hotel_id </if> ORDER BY sort ASC,th.id DESC
06-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值