folly::Function vs std::function
#한 줄 요약
folly::Function<Sig>는 move-only callable wrapper다. std::function이 callable에 CopyConstructible를 요구해 unique_ptr 캡처를 못 받는 문제를 해결한다. 추가로 const-correctness와 exec policy(once/non-once)를 명시할 수 있다.
#동기 — std::function의 두 가지 한계
#1. CopyConstructible 요구
auto ptr = std::make_unique<HeavyState>();
std::function<void()> f = [ptr = std::move(ptr)]() { ptr->doWork();};// 컴파일 에러 — std::function은 callable이 CopyConstructible여야 함// unique_ptr capture는 copy 불가std::function은 type erasure 안에서 callable을 copy할 수 있어야 한다. unique_ptr 같은 move-only state는 못 담는다. 우회하려면 shared_ptr로 감싸야 하는데 atomic refcount 비용.
#2. const-correctness 부족
std::function<void()> f = [state](mutable) { state.modify(); };// const std::function&으로 받아도 operator()는 non-const로 호출 가능// → const-correctness 깨짐std::function::operator()가 const 메서드라 const ref로 받아도 호출되는데, 내부 callable이 mutable이면 실제로 상태가 변한다.
#folly::Function
#include <folly/Function.h>
auto ptr = std::make_unique<HeavyState>();folly::Function<void()> f = [ptr = std::move(ptr)]() { ptr->doWork();}; // OK — folly::Function은 move-only
// const-correctnessfolly::Function<void() const> cf = [](){ /* must not mutate */ };// folly::Function<void()>와 다른 타입API.
folly::Function<Ret(Args...)> // non-const, callable mutable OKfolly::Function<Ret(Args...) const> // const, callable must not mutatefolly::Function<Ret(Args...) &&> // once-only, exec 후 self consumestd::function처럼 type erasure이지만 move-only.
#내부 구현 — SBO
template <typename Sig>class Function { union { char inline_buf_[sizeof(void*) * 6]; // SBO void* heap_; }; // dispatch table struct VTable { Ret (*invoke)(Function*, Args...); void (*move)(Function*, Function*); void (*destroy)(Function*); }; const VTable* vtable_;};callable이 작으면 inline_buf_에 in-place (SBO, ~48 bytes), 크면 heap에 alloc. std::function과 거의 같은 SBO 크기.
VTable은 invoke/move/destroy만 — copy가 없다. 이게 move-only의 핵심.
#once-only — && qualifier
folly::Function<void() &&> once = [&]() { // self를 소비하고 끝 (한 번만 호출 가능)};
std::move(once)(); // OKonce(); // 컴파일 에러std::move(once)(); // 런타임 abort (이미 호출됨)callback이 한 번만 실행됨이 type level에서 보장된다. Future의 thenValue 콜백이 이 패턴.
#std::function와 비교
| 항목 | std::function | folly::Function |
|---|---|---|
| CopyConstructible 요구 | yes | no |
| unique_ptr capture | x | o |
| const callable 구분 | x | o (Sig const) |
| once-only | x | o (Sig &&) |
| SBO 크기 | 구현마다 다름, ~32B | ~48B (6 ptr) |
| std 호환 변환 | — | std::function ← folly::Function 변환 가능 |
#코드 리뷰 포인트
#1. callback API는 folly::Function 우선
// 회피 — unique_ptr capture 불가void addCallback(std::function<void()> cb);
// Good — move-only 받음void addCallback(folly::Function<void()> cb);
addCallback([p = std::make_unique<X>()]() { p->run(); });특히 비동기 API는 move-only가 자연스럽다.
#2. const 명시
// 회피 — 의도가 const-readonly인데 non-constfolly::Function<void()> f;
// Good — readonly임을 명시folly::Function<void() const> f;내부 callable이 state를 안 바꾼다면 const로 표시. type 시스템이 보장.
#3. once-only 명시
// 회피 — Promise.set 콜백, 한 번만 호출되는데 일반 Functionfolly::Function<void(Result)> cb;
// Good — once-only 명시folly::Function<void(Result) &&> cb;콜백이 한 번만 실행됨을 type으로 알리면 caller가 잘못 보관 불가.
#4. std::function로 변환
folly::Function<int()> ff = []{ return 1; };std::function<int()> sf = std::move(ff).asSharedProxy(); // copy 가능하게 변환외부 API가 std::function을 요구하면 변환 helper 사용. asSharedProxy는 내부에서 shared_ptr로 감싸 copyable로.
#성능 비교
| std::function | folly::Function | |
|---|---|---|
| empty 생성 | ~1ns | ~1ns |
| SBO 호출 | ~3ns | ~3ns |
| heap callable 호출 | ~5ns | ~5ns |
| copy | yes (callable copy) | n/a (move-only) |
| move | swap | swap |
성능은 사실상 동일. 차이는 표현력(move-only, const, once-only).
#안티패턴
#1. shared_ptr로 우회
// 회피 — folly::Function 쓰면 됨auto ptr = std::make_shared<HeavyState>();std::function<void()> f = [ptr] { ptr->doWork(); };shared_ptr atomic 비용 + 의미 불명확(왜 shared인지). folly::Function이 명료.
#2. once-only를 일반 Function으로
// 회피folly::Function<void()> cb = [&]() { /* 한 번만 */ };runner.setCallback(std::move(cb));runner.setCallback(std::move(cb)); // 한 번 후 호출, 미정의once-only면 && qualifier로 명시.
#3. const Function&으로 받아 mutate
// 회피void run(const folly::Function<void()>& f) { f(); // const Function의 callable은 non-const일 수도? Folly는 type level 구분}
// Goodvoid run(folly::Function<void() const>& f); // 명확const Function vs non-const Function vs Function<void() const>의 구분을 의식.
#정리
- folly::Function은 move-only callable.
- unique_ptr 같은 move-only state를 캡처 가능.
- const qualifier(
Sig const)로 callable의 const-correctness. &&qualifier로 once-only 콜백 명시.- SBO 약 48B, 그 외 heap alloc.
- std::function과 호환 변환 (asSharedProxy).
- async/콜백 API는 folly::Function이 기본.
#다음 편
Part 13-05 Lazy — 지연 초기화 wrapper. once_flag 패턴을 type level로.
#관련 항목
- Part 2-04 thenValue / thenError — once-only 콜백 사용
- Effective Modern C++ Item 33 — init capture와 move-only lambda
- Effective Modern C++ Item 34 — std::function 한계
Folly Code Review · 60 of 89
- 1 Folly Code Review — Meta의 production-grade C++ 라이브러리 코드 분석
- 2 Folly 개요 — Meta가 production에서 검증한 utility 모음 분석
- 3 Folly vs Abseil 철학 비교 — performance-first vs std-compatible
- 4 Folly 빌드와 fbcode 환경 — monorepo의 그림자
- 5 Folly API stability 정책 — 어떤 보장도 없다는 솔직함
- 6 Folly production validation 문화 — peta-scale에서 단련된 코드
- 7 folly::Future 분석 — std::future의 한계를 넘는 composable async
- 8 folly::Promise·makeFuture — Future를 만드는 두 길
- 9 folly::SemiFuture vs Future — executor binding의 명시화
- 10 folly::Future thenValue·thenError·thenTry — continuation 체인 분석
- 11 folly::collect·collectAll·collectAny — fan-in 패턴 분석
- 12 folly::Future retry·window·via — 제어 흐름 조합자
- 13 folly::fibers 분석 — M:N stackful coroutine
- 14 folly::InlineExecutor — 호출자 thread에서 즉시 실행
- 15 folly::CPUThreadPoolExecutor — CPU-bound 작업의 표준 thread pool
- 16 folly::IOThreadPoolExecutor — libevent 기반 I/O pool
- 17 folly::ManualExecutor — 결정적 테스트를 위한 수동 진행
- 18 folly::EventBase 분석 — libevent 이벤트 루프의 핵심
- 19 folly::IOBuf 분석 — zero-copy buffer chain의 기본 단위
- 20 folly::IOBufQueue — chain의 push/pull 추상화
- 21 folly::io::Cursor·RWCursor — chain 위의 stream
- 22 folly Zero-copy 패턴 — IOBuf로 ScatterGather I/O 표현
- 23 folly::IOBuf shared semantics — clone·unshare·takeOwnership
- 24 folly::FBString 분석 — SSO + COW 구현
- 25 folly의 fmt::format 통합 — 모던 포맷팅 채택
- 26 folly::StringPiece — string_view 호환 분석
- 27 folly Join·Split utilities — 문자열 분해와 결합
- 28 folly::to·tryTo — text↔num 변환 분석
- 29 folly Conv Customization — 사용자 타입 지원
- 30 folly Conv 성능 비교 — sprintf·stringstream 대비
- 31 folly::F14ValueMap vs std::unordered_map
- 32 folly::F14NodeMap — stable pointer가 필요할 때
- 33 folly::F14VectorMap — cache-friendly iteration
- 34 folly::F14FastMap — auto-select 동작
- 35 folly F14 internals — SIMD probing 메커니즘
- 36 folly::small_vector — inline storage 분석
- 37 folly::FixedString — compile-time string
- 38 folly::AtomicHashMap — lock-free read 분석
- 39 folly::ConcurrentHashMap — sharded 동시 해시 맵
- 40 folly::EvictingCacheMap — LRU 구현 분석
- 41 folly::Synchronized — lock wrapper 패턴
- 42 folly::SharedMutex 분석
- 43 folly::Baton — one-shot wait 동기화
- 44 folly::RWSpinLock 분석
- 45 folly::PicoSpinLock — 1-byte spinlock
- 46 folly::ProducerConsumerQueue — SPSC 큐 분석
- 47 folly::MPMCQueue — multi-producer multi-consumer
- 48 folly::UnboundedQueue — 동적 크기 lock-free
- 49 folly::fibers::Channel — Go-like channel
- 50 folly::dynamic — JSON-like dynamic type 분석
- 51 folly JSON conversion — toJson·parseJson
- 52 folly dynamic ↔ struct — manual marshaling
- 53 folly dynamic Visitor pattern — type별 분기
- 54 folly::Singleton vs Meyers/static — 왜 Folly의 Singleton인가
- 55 folly::SingletonVault 분석 — 등록·소멸·의존성
- 56 folly::Singleton try_get·try_get_fast — TLS-cached 접근
- 57 folly::ExceptionWrapper — type-erased exception holder
- 58 folly::ScopeGuard·SCOPE_EXIT — RAII cleanup
- 59 folly::Optional vs std::optional
- 60 folly::Function vs std::function
- 61 folly::Lazy — 지연 초기화 wrapper
- 62 folly Meta 스타일 code review 패턴
- 63 folly anti-patterns — 잘못 쓰면 std보다 느림
- 64 folly vs std 선택 기준 분석
- 65 folly::coro 개요 — production C++20 코루틴 어댑터
- 66 folly::coro::Task — lazy single-shot 코루틴
- 67 folly::coro::AsyncGenerator — 비동기 스트림
- 68 folly coro blockingWait·collectAll — 동기 경계와 fan-in
- 69 folly::coro::Baton·Mutex — 코루틴-aware 동기화
- 70 folly::Expected — 결과 또는 오류
- 71 folly::Try — Future 결과 wrapper
- 72 folly::Try vs Expected 선택 기준
- 73 folly::Range — 일반 iterator pair
- 74 folly::Uri — URL 파서
- 75 folly Fingerprint64·128 — 분산 hash
- 76 folly SpookyHashV2 — fast non-crypto hash
- 77 folly::Init — main() 부트스트랩
- 78 folly::Indestructible — global lifetime 패턴
- 79 folly::MicroLock — 1-byte 락
- 80 folly::MicroSpinLock — 가장 좁은 spin lock
- 81 folly::format — legacy formatter 분석
- 82 folly::demangle — typeid 디망글링
- 83 folly::DynamicConverter — dynamic ↔ struct
- 84 folly::RecordIO — append-only 로그 파일 포맷
- 85 folly::io::Compression — zstd·lz4·snappy wrapper
- 86 folly::AsyncIO — io_uring·Linux AIO
- 87 folly::CancellationToken — 코루틴·Future 취소 전파
- 88 folly::observer — hot config의 atomic refresh
- 89 fbcode 패턴 모음 — folly 사용의 실전
관련 글
fbcode 패턴 모음 — folly 사용의 실전
Meta fbcode 코드 리뷰에서 반복적으로 등장하는 folly 사용 패턴 — overview + 시리즈 마무리.
같은 시리즈에서 이어 읽기
folly::observer — hot config의 atomic refresh
folly::observer — read mostly 값의 atomic refresh, hot config·feature flag·LB weight 같은 패턴의 표준.
같은 시리즈에서 이어 읽기
folly::CancellationToken — 코루틴·Future 취소 전파
CancellationSource/Token의 전파 모델 — coroutine·Future·callback 트리에서 협력적 취소.
같은 시리즈에서 이어 읽기