/**
* 这个测试主要是模拟变量在内存位置发生移动后,之前通过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指针,是已经析构的对象!如果有逻辑调用,就会崩溃了。
*/
c++ this指针在对象移动后失效
最新推荐文章于 2024-09-11 16:11:22 发布
文章讨论了在C++中,当对象内存位置改变时,通过`this`注册的事件会失效。通过使用智能指针管理,可以确保即使对象被复制或移动,事件处理逻辑仍保持正确。
摘要由CSDN通过智能技术生成