Why the std::function object(i.e fn) still works well after the object ins is out of scope? Here is the code snappit(https://godbolt.org/z/Y6KaWY):
#include <iostream>
#include <functional>
std::function<int(void)> fn;
class CTest
{
public:
CTest() {std::cout << "ctor:" << this << std::endl;};
int demo(void){std::cout << "this pointer:" << this << std::endl; return 0;}
};
void assign(void)
{
CTest ins;
fn = std::bind(&CTest::demo, &ins);
}
int foo()
{
return 9;
}
int main()
{
assign();
CTest tes1;
foo();
fn();
}
The outputs: Program returned: 0 Program stdout ctor:0x7fff64960a80 ctor:0x7fff64960be0 this pointer:0x7fff64960a80 //You see, still point to the object(i.e ins) that is out of its scope
Aucun commentaire:
Enregistrer un commentaire