c++ this指针在对象移动后失效

文章讨论了在C++中,当对象内存位置改变时,通过`this`注册的事件会失效。通过使用智能指针管理,可以确保即使对象被复制或移动,事件处理逻辑仍保持正确。
摘要由CSDN通过智能技术生成
/**
 * 这个测试主要是模拟变量在内存位置发生移动后,之前通过this注册的一些事件,就失效了,所以只能通过智能指针管理才是设计上不容易出错。
 */

#include <cstdio>
#include <functional>
#include <string>
#include <utility>

std::function<void()> on_some_event;

struct MyTest {
  explicit MyTest(std::string name) : name(std::move(name)) {
    printf("MyTest: %s: %p\n", this->name.c_str(), this);
  }

  void init() {
    auto this_ptr = this;  // 这里主要是想说明,捕获this实际上等价捕获一个常量:this_ptr
    on_some_event = [this, this_ptr] {
      // 关键是这里:当this指向的对象,被拷贝或者move,这个this并不会变化。
      // 1. 如何保证this有效呢?
      // 2. 判断已经失效就return 这种逻辑能保证不崩溃,但是想要的逻辑没有了。
      printf("on_some_event: this saved in lambda: %p, %p\n", this, this_ptr);
    };
  }

  void print() {
    printf("print: %s: %p\n", name.c_str(), this);
  }

  ~MyTest() {
    printf("~MyTest: %s: %p\n", name.c_str(), this);
  }

  std::string name;
};

MyTest create_object() {
  MyTest test_tmp("test");
  test_tmp.init();
  return std::move(test_tmp);  // 这里一定要加std::move 避免自动返回值优化 否则就测不出来问题了
}

int main() {
  MyTest test = create_object();
  test.print();

  on_some_event();
  return 0;
}

/**
MyTest: test: 0x16ae02e00
~MyTest: test: 0x16ae02e00
print: test: 0x16ae02e50
on_some_event: this saved in lambda: 0x16ae02e00, 0x16ae02e00
~MyTest: test: 0x16ae02e50


注意on_some_event打印的this指针,是已经析构的对象!如果有逻辑调用,就会崩溃了。
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值