【发布时间】:2016-01-16 11:17:30
【问题描述】:
我有以下例子:
#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 )
这会导致运行时错误。我猜这是因为我的回调中只存储了对成员函数的引用,而不是调用成员的对象。
我不明白std::ref 在我做Obj() : t(std::ref(*this)) 时做了什么,以及为什么这会使程序工作。任何人都可以阐明发生了什么以及它是如何工作的吗?
【问题讨论】:
-
否
Obj() : t(*this)工作正常。您的Callback是函子类型,您的Obj也是。 -
@Jean-BaptisteYunès 你是说编译器生成无效代码,因为
Obj() : t(*this)在运行时崩溃,但它应该可以正常工作? -
它适用于我的 g++ std c++11 编译器,我不明白为什么它不适合你。
-
因为
*this当时正在建设中,它的值可以无效是不是真的很奇怪...? -
@binary01 你没有通过
this,你通过了*this
标签: c++