使用 t( *this ) 会导致运行时错误,而 t( std::ref( *this ) 则不会
Using t( *this ) results RuntimeError, while t( std::ref( *this ) does not
我有以下示例:
#include <iostream>
#include <functional>
struct Tmr {
typedef std::function<void(void)> Callback;
Callback cb;
Tmr(Callback cb_) :
cb( cb_ )
{
}
void timeout()
{
cb();
}
};
struct Obj {
struct Tmr t;
Obj() :
t( std::ref( *this ) )
{
}
void operator () ()
{
std::cout << __func__ << 'n';
}
};
int main(int argc, char *argv[])
{
Obj o;
o.t.timeout();
return 0;
}
这运行良好,但最初我将Obj
的构造函数设置为:
Obj() :
t( *this )
这会导致运行时错误。我想这是因为我的回调中只存储了对成员函数的引用,而不是调用成员的对象。
我不明白的是,当我做Obj() : t(std::ref(*this))
时,std::ref
做了什么,以及为什么这会让程序工作。任何人都可以阐明正在发生的事情及其工作原理吗?
当你不通过引用传递时,你会在初始化t
之前复制*this
- 这意味着你在初始化之前复制t
及其回调成员,这是未定义的行为。
(std::function
的复制构造函数可能会尝试复制未初始化指针指向的内容,这就是导致实际崩溃的原因。
由于复制未初始化的回调对象,您的代码崩溃。您可以在下面看到一系列事件:
1. Copy constructor of Obj is called in t(*this)
2. Copy constructor of Tmr is called as t is a member of Obj
3. Copy constructor of Callback is called as cb is a member of Tmr
4. Execution fails while trying to copy from uninitialized Callback object.
通过使用 std::ref,您可以绕过 Obj 的副本创建;这就是它不会崩溃的原因。
相关文章:
- 表示"accepting anything for this template argument" C++概念的通配符
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将Ref对象作为类成员
- 为什么我的 std::ref 无法按预期工作?
- C++错误:"error: int aaa::bbb is protected within this context"
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 关于C++中具有多重继承"this"指针的说明
- 在noexcept 规范中是否允许使用"this"?
- 如何将 Eigen::Ref 与 pybind11 一起使用?
- 如何修复"error: ‘_1’ was not declared in this scope"?
- 如何@ref同一方法的不同变体?
- C++调用具有 *this 属性的单个帮助程序函数
- Doees the 'this' 指针参与虚函数的多态行为
- 在 c++ 中正确定义"this"关键字?
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- 使用 t( *this ) 会导致运行时错误,而 t( std::ref( *this ) 则不会