|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | + |
| 4 | +#include <cassert> |
| 5 | +#include <functional> |
| 6 | + |
| 7 | +#pragma warning(disable : 4324) // 'large_callable': structure was padded due to alignment specifier |
| 8 | + |
| 9 | +using namespace std; |
| 10 | + |
| 11 | +struct copy_counter { |
| 12 | + copy_counter() = default; |
| 13 | + copy_counter(const copy_counter& other) : count(other.count + 1) {} |
| 14 | + |
| 15 | + int count = 0; |
| 16 | +}; |
| 17 | + |
| 18 | +using function_type = int(copy_counter); |
| 19 | + |
| 20 | +struct small_callable { |
| 21 | + int context = 42; |
| 22 | + |
| 23 | + int operator()(const copy_counter& counter) { |
| 24 | + assert(context == 42); |
| 25 | + return counter.count; |
| 26 | + } |
| 27 | +}; |
| 28 | + |
| 29 | +struct alignas(128) large_callable { |
| 30 | + int context = 1729; |
| 31 | + |
| 32 | + int operator()(const copy_counter& counter) { |
| 33 | + assert(context == 1729); |
| 34 | + return counter.count; |
| 35 | + } |
| 36 | +}; |
| 37 | + |
| 38 | +int main() { |
| 39 | + // Plain calls |
| 40 | + { |
| 41 | + function<function_type> fn{small_callable{}}; |
| 42 | + assert(fn(copy_counter{}) == 0); |
| 43 | + } |
| 44 | + { |
| 45 | + function<function_type> fn{large_callable{}}; |
| 46 | + assert(fn(copy_counter{}) == 0); |
| 47 | + } |
| 48 | + { |
| 49 | + move_only_function<function_type> fn{small_callable{}}; |
| 50 | + assert(fn(copy_counter{}) == 0); |
| 51 | + } |
| 52 | + { |
| 53 | + move_only_function<function_type> fn{large_callable{}}; |
| 54 | + assert(fn(copy_counter{}) == 0); |
| 55 | + } |
| 56 | + |
| 57 | + // Moves to the same |
| 58 | + { |
| 59 | + function<function_type> fn{function<function_type>{small_callable{}}}; |
| 60 | + assert(fn(copy_counter{}) == 0); |
| 61 | + } |
| 62 | + { |
| 63 | + function<function_type> fn{function<function_type>{large_callable{}}}; |
| 64 | + assert(fn(copy_counter{}) == 0); |
| 65 | + } |
| 66 | + { |
| 67 | + move_only_function<function_type> fn{move_only_function<function_type>{small_callable{}}}; |
| 68 | + assert(fn(copy_counter{}) == 0); |
| 69 | + } |
| 70 | + { |
| 71 | + move_only_function<function_type> fn{move_only_function<function_type>{large_callable{}}}; |
| 72 | + assert(fn(copy_counter{}) == 0); |
| 73 | + } |
| 74 | + |
| 75 | + // Moves from function to move_only_function |
| 76 | + { |
| 77 | + move_only_function<function_type> fn{function<function_type>{small_callable{}}}; |
| 78 | + assert(fn(copy_counter{}) == 1); |
| 79 | + } |
| 80 | + { |
| 81 | + move_only_function<function_type> fn{function<function_type>{large_callable{}}}; |
| 82 | + assert(fn(copy_counter{}) == 1); |
| 83 | + } |
| 84 | +} |
0 commit comments