[英]std::function to member function of object and lifetime of object
如果我有一個綁定到對象實例的成員函數的std::function
實例,並且該對象實例超出范圍而被破壞,那么我的std::function
對象現在將被視為一個錯誤的指針如果打電話失敗?
例:
int main(int argc,const char* argv){
type* instance = new type();
std::function<foo(bar)> func = std::bind(type::func,instance);
delete instance;
func(0);//is this an invalid call
}
標准中是否有某些內容指明應該發生什么? 我的預感是它將拋出異常,因為該對象不再存在
編輯:標准是否指定應該發生什么?
是不確定的行為?
編輯2:
#include <iostream>
#include <functional>
class foo{
public:
void bar(int i){
std::cout<<i<<std::endl;
}
};
int main(int argc, const char * argv[]) {
foo* bar = new foo();
std::function<void(int)> f = std::bind(&foo::bar, bar,std::placeholders::_1);
delete bar;
f(0);//calling the dead objects function? Shouldn't this throw an exception?
return 0;
}
運行此代碼我收到輸出值0;
會發生什么是未定義的行為。
bind()
調用將返回一些包含instance
副本的對象,這樣當你調用func(0)
會有效地調用:
(instance->*(&type::func))(0);
如果instance
是delete
d,則取消引用無效指針是未定義的行為。 它不會拋出異常(雖然,它是未定義的,所以它可以,誰知道)。
請注意,您在通話中錯過了占位符:
std::function<foo(bar)> func =
std::bind(type::func, instance, std::placeholders::_1);
// ^^^^^^^ here ^^^^^^^^^
沒有它,即使使用未刪除的實例,也無法調用func(0)
。
更新示例代碼以更好地說明正在發生的事情:
struct foo{
int f;
~foo() { f = 0; }
void bar(int i) {
std::cout << i+f << std::endl;
}
};
使用添加的析構函數,您可以看到復制指針(在f
)和復制指向的對象(以g
)之間的區別:
foo* bar = new foo{42};
std::function<void(int)> f = std::bind(&foo::bar, bar, std::placeholders::_1);
std::function<void(int)> g = std::bind(&foo::bar, *bar, std::placeholders::_1);
f(100); // prints 142
g(100); // prints 142
delete bar;
f(100); // prints 100
g(100); // prints 142 still, because it has a copy of
// the object bar pointed to, rather than a copy
// of the pointer
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.