[英]Is it safe to use std::bind on an uninitialized object?
由於我無法正確設計課程,我達到了需要這樣的地步:
struct A
{
A( function< void(string&) cb > ): callback(cb) {}
function< void(string&) > callback;
template <std::size_t T>
void func( string& str) { ... }
}
int main(){
vector<A> items = {
A( bind( &A::func<1>, items[0], _1) ),
A( bind( &A::func<2>, items[1], _1) ),
...
}
這樣安全嗎? 如果沒有,有替代方案嗎?
這當然不安全。 在初始化items
之前將評估items[0]
。
在這里做的正確的事情可能只是使用lambda,就像
vector<A> items = {
A( [&items](string& s){ items[0].func(s); } ),
A( [&items](string& s){ items[1].func(s); } ),
...
}
這僅在初始化期間獲取對items
的引用,然后僅在實際調用回調時才提取items[0]
。
或者,您是否可以更改回調以將A&
作為參數? 如果你的回調類型是std::function<void(A&, string&)>
那么你可以傳遞&A::func<1>
作為回調,它將起作用。
您正在使用[]
運算符在構造之前訪問vector
。 這不安全。
我想你將不得不在vector
創建非完全初始化的項目,然后再設置bindee。
main
的代碼創建一個固定大小的向量。 如果這實際上是必需的,請使用數組或std::array
,並將該元素的地址傳遞給bind
調用:
A items[] = {
A( bind( &A::func<1>, &items[0], _1) ),
A( bind( &A::func<2>, &items[1], _1) ),
...
};
bind
返回的函數對象知道如何綁定指向對象的指針和成員函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.