В моей реализации я предоставляю оптимизацию небольших объектов (a.k.a Soo) для моего кода, который в основном представляет собой союз, который хранит как указатель функции, так и указатель стира , Я могу использовать новое размещение для хранения обернутого объекта непосредственно в области памяти, где находится объединение, а затем получить к нему доступ p>
Код: Выделить всё
template
class UniqueFunction;
template
class UniqueFunction {
struct AnyFn {
virtual ~AnyFn() noexcept = default;
virtual Ret operator()( Args... args ) = 0;
};
template
struct FnContainer : public AnyFn {
Fn fntor_;
FnContainer( Fn fntor ) : fntor_ { std::move( fntor ) } {}
FnContainer( const FnContainer& ) = delete;
FnContainer& operator=( const FnContainer& ) & = delete;
virtual ~FnContainer() noexcept = default;
Ret operator()( Args... args ) override { return fntor_( std::forward( args )... ); }
};
union {
typename std::add_pointer::type fptr_;
AnyFn* ftor_;
} data_; // The union is here.
// Tag that identifies the type of data currently stored in the union.
enum class Tag : std::uint8_t { None, Fptr, FtorInline, FtorDync } tag_;
// other methods...
};
Подробнее здесь: https://stackoverflow.com/questions/794 ... ub-for-soo
Мобильная версия