아래 코드에 어떤 문제가 있습니까?람다 펑터 할당 해결 방법
#include <iostream>
#include <type_traits>
template <typename T>
void assign_lambda(T&& f)
{
typedef typename std::remove_reference<T>::type functor_type;
typedef typename std::aligned_storage<sizeof(functor_type),
std::alignment_of<functor_type>::value>::type buffer_type;
static char store[sizeof(buffer_type)];
auto const p(new (store) functor_type(std::forward<T>(f)));
(*p)();
}
int main()
{
for (int i(0); i != 5; ++i)
{
assign_lambda([i](){ std::cout << i << std::endl; });
}
return 0;
}
비표준이거나 위험 할 수 있습니다.
편집 : char
어레이로 초기화하는 이유는 무엇입니까? 힙에서 크기가 sizeof(buffer_type)
인 블록을 할당하고 블록이 충분히 커야하는 경우 반복 할당 (예 : 반복 메모리 할당 방지)을 위해 재사용 할 수 있습니다.
void * operator new (std :: size_t size);
효과 : 할당 함수 (3.7.4.1)는 해당 크기의 모든 객체를 나타 내기 위해 적절히 정렬 된 저장소의 크기 바이트를 할당하기 위해 새 표현식 (5.3.4)을 호출합니다.
힙에서 할당하면 정렬 문제가 사라집니다.
다중 스레드 환경에서 제대로 작동하지 않습니다 – bobah
@bobah mutex가 수정할 수없는 것은 없습니다. – user1095108
'std :: function'의 문제점은 무엇입니까? – sehe