Better_Software_Header_Mobile Better_Software_Header_Web

Find what you need - explore our website and developer resources

Qt and Trivial Relocation (Part 6)

struct Person
{
    QString firstName;
    QString lastName;
};
Q_DECLARE_TYPEINFO(Person, Q_RELOCATABLE_TYPE);
template <typename T>
constexpr bool isRelocatable = QTypeInfo<T>::isRelocatable;

consteval bool isRelocatableType(std::meta::info type)
{
    return extract<bool>(substitute(^^isRelocatable, { type }));
}

template <typename T>
consteval bool isEligible()
{
    constexpr auto ctx = std::meta::access_context::unchecked();

    for (std::meta::info member : nonstatic_data_members_of(^^T, ctx)) {
        if (!isRelocatableType(type_of(member)))
            return false;
    }

    for (std::meta::info base : bases_of(^^T, ctx)) {
        if (is_virtual(base) || !isRelocatableType(type_of(base)))
            return false;
    }

    return true;
}
template <typename T>
consteval bool isAutomaticallyRelocatable()
{
    if (std::is_trivially_copyable_v<T>)
        return true;

    if (!isEligible<T>())
        return false;

    constexpr auto ctx = std::meta::access_context::unchecked();

    return std::ranges::none_of(members_of(^^T, ctx), [](std::meta::info member) {
        return (is_copy_constructor(member) || is_move_constructor(member)
                || is_copy_assignment(member) || is_move_assignment(member)
                || is_destructor(member))
            && is_user_provided(member);
    });
}
class Contact
{
public:
    Contact();
    Contact(const Contact &other);
    Contact(Contact &&other) noexcept;
    Contact &operator=(const Contact &other);
    Contact &operator=(Contact &&other) noexcept;
    ~Contact();

private:
    QString m_name;
    std::string m_email;  // oops
};

Q_DECLARE_TYPEINFO(Contact, Q_RELOCATABLE_TYPE);
error: static assertion failed: The type Contact is not structurally trivially relocatable

Tags:

c++qt

GiuseppeD'Angelo

Giuseppe D’Angelo

Senior Software Engineer

Sign up for the KDAB Newsletter

Learn Modern C++

Learn more