| 348 | /// Special internal constructor for functors, lambda functions, etc. |
| 349 | template <typename Func, typename Return, typename... Args, typename... Extra> |
| 350 | void initialize(Func &&f, Return (*)(Args...), const Extra &...extra) { |
| 351 | using namespace detail; |
| 352 | struct capture { |
| 353 | remove_reference_t<Func> f; |
| 354 | |
| 355 | static capture *from_data(void **data) { |
| 356 | return PYBIND11_STD_LAUNDER(reinterpret_cast<capture *>(data)); |
| 357 | } |
| 358 | }; |
| 359 | |
| 360 | /* Store the function including any extra state it might have (e.g. a lambda capture |
| 361 | * object) */ |
| 362 | // The unique_ptr makes sure nothing is leaked in case of an exception. |
| 363 | auto unique_rec = make_function_record(); |
| 364 | auto *rec = unique_rec.get(); |
| 365 | |
| 366 | /* Store the capture object directly in the function record if there is enough space */ |
| 367 | if (sizeof(capture) <= sizeof(rec->data)) { |
| 368 | /* Without these pragmas, GCC warns that there might not be |
| 369 | enough space to use the placement new operator. However, the |
| 370 | 'if' statement above ensures that this is the case. */ |
| 371 | PYBIND11_WARNING_PUSH |
| 372 | |
| 373 | #if defined(__GNUG__) && __GNUC__ >= 6 |
| 374 | PYBIND11_WARNING_DISABLE_GCC("-Wplacement-new") |
| 375 | #endif |
| 376 | |
| 377 | new (capture::from_data(rec->data)) capture{std::forward<Func>(f)}; |
| 378 | |
| 379 | #if !PYBIND11_HAS_STD_LAUNDER |
| 380 | PYBIND11_WARNING_DISABLE_GCC("-Wstrict-aliasing") |
| 381 | #endif |
| 382 | |
| 383 | // UB without std::launder, but without breaking ABI and/or |
| 384 | // a significant refactoring it's "impossible" to solve. |
| 385 | if (!std::is_trivially_destructible<capture>::value) { |
| 386 | rec->free_data = [](function_record *r) { |
| 387 | auto data = capture::from_data(r->data); |
| 388 | (void) data; // suppress "unused variable" warnings |
| 389 | data->~capture(); |
| 390 | }; |
| 391 | } |
| 392 | PYBIND11_WARNING_POP |
| 393 | } else { |
| 394 | rec->data[0] = new capture{std::forward<Func>(f)}; |
| 395 | rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); }; |
| 396 | } |
| 397 | |
| 398 | /* Type casters for the function arguments and return value */ |
| 399 | using cast_in = argument_loader<Args...>; |
| 400 | using cast_out |
| 401 | = make_caster<conditional_t<std::is_void<Return>::value, void_type, Return>>; |
| 402 | |
| 403 | static_assert( |
| 404 | expected_num_args<Extra...>( |
| 405 | sizeof...(Args), cast_in::args_pos >= 0, cast_in::has_kwargs), |
| 406 | "The number of argument annotations does not match the number of function arguments"); |
| 407 |
nothing calls this directly
no test coverage detected