두 람다 함수 사이에 포함 범위의 변수를 공유 할 수 있기를 원합니다. 다음이 있습니다.
void holdAdd(const Rect& rectangle, Hold anonymousHeld, Hold anonymousFinish) {
std::map<int,bool> identifierCollection;
HoldFinish holdFinish = [=](const int& identifier) mutable {
if (identifierCollection.count(identifier) == 0) return;
identifierCollection.erase(identifier);
anonymousFinish();
};
holdCollisionCollection.push_back([=](const int& identifier, const Vec2& point) mutable {
if (rectangle.containsPoint(point)) {
identifierCollection[identifier] = true;
anonymousHeld();
} else {
holdFinish(identifier);
}
});
holdFinishCollection.push_back(holdFinish);
}
두 번째 람다 함수와 holdFinish
다른 구현을 가리키는 디버거에서 볼 수 있습니다 identifierCollection
.
내가 사용 [=, &identifierCollection]
하면 사용 EXC_BAD_ACCESS
여부를 던집니다 mutable
.
인라인 함수를 구현하는 다른 언어에 대한 나의 경험은 이것이 가능해야한다는 것입니다. 예를 들어 javascript에서 :
var a = 10;
var b = function() {
a += 2;
}
var c = function() {
a += 3;
}
b();
c();
alert(a);
경고 할 것 15
입니다.
두 람다 함수가 동일한 identifierCollection 구현을 참조하도록하려면 어떻게해야합니까? 따라서 자바 스크립트 예제와 동일한 방식으로 작동합니다.
Unlike in some scripting languages, identifierCollection
's lifetime won't be extended simply because you captured it into a closure. So as soon as you change that [=]
for a [&]
to capture by reference, it's a dangling reference to a local variable that you're capturing.
You'll have to manage the lifetime of identifierCollection
yourself; frankly, this sounds like the perfect opportunity for a shared pointer, captured by value into each lambda. The dynamically-allocated map it wraps will literally exist for as long as you need it to.
void holdAdd(const Rect& rectangle, Hold anonymousHeld, Hold anonymousFinish)
{
auto identifierCollection = std::make_shared<std::map<int,bool>>();
HoldFinish holdFinish = [=](const int& identifier) mutable {
if (identifierCollection->count(identifier) == 0) return;
identifierCollection->erase(identifier);
anonymousFinish();
};
holdCollisionCollection.push_back([=](const int& identifier, const Vec2& point) mutable {
if (rectangle.containsPoint(point)) {
(*identifierCollection)[identifier] = true;
anonymousHeld();
} else {
holdFinish(identifier);
}
});
holdFinishCollection.push_back(holdFinish);
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다