次のコードはSegmentation Fault、y = anotherFunctor()行に a を生成します。私が理解している限り、これは、作成globalFunctor時に変数が存在しないために発生しますanotherFunctor。std::function<int(int)>しかし、に置き換えるとなぜ機能するのGlobalFunctorですか? どうすれば修正できますか?
#include <functional>
struct GlobalFunctor
{
int operator()() const { return 42; }
};
extern GlobalFunctor globalFunctor;
struct AnotherFunctor
{
AnotherFunctor() : g_(globalFunctor) {}
int operator()() const { return g_(); }
const std::function<int()>& g_;
} anotherFunctor;
GlobalFunctor globalFunctor;
int main()
{
AnotherFunctor af;
int x = af();
int y = anotherFunctor();
int z = x + y;
return 0;
}
編集:clang代わりにこれをコンパイルしようとしましたがgcc、警告が表示されますbinding reference member 'g_' to a temporary valueが、これをコンパイルするとクラッシュします。キャストstd::functionは一時的な参照を作成しますか?