Friday, 4 December 2026
Qt and Trivial Relocation (Part 6)
An experiment with C++26 reflection
It's been a while since the last instalment of this series! Back then, I wrote that having trivial relocation in C++26 was "doable". Well... it didn't quite go that way: P2786 was merged into the C++26 draft in February 2025, and then removedin November of the same year. C++26 is going to ship without trivial relocation.
I've just given a talk at Meeting C++ about the whole story. I'd suggest you catch up with the recording as soon as it gets online; and if you have any questions about the content, please ask me!
The C++29 cycle has now started, and for trivial relocation there are still design decisions to make. I've published a paper about them, P4197 ("Design questions for trivial relocation in C++29"). Once we agree on the design, I'd like to get to the feature layer by layer: starting from the building blocks in the library, like algorithms and containers, and then working our way up into the core language. I'm not going to talk about C++29 in this post, though.
This post is a bit different from the previous ones: I'd like to show you a small experiment. C++26 may not have trivial relocation, but it does have reflection. Can we use it to make Qt's own trivial relocation easier and safer to use?
What was the problem again?
In the first post I claimed that there is no way to know "from the outside" if a generic type can be moved in memory via memcpy. Qt plays it safe: unless a type is trivially copyable, Qt assumes that it is not trivially relocatable. If it is, you have to say so, using a macro.
Consider this very simple type:
struct Person
{
QString firstName;
QString lastName;
};QString is trivially relocatable, therefore Person is trivially relocatable as well. But Qt doesn't know that! We have to remember to add this:
Q_DECLARE_TYPEINFO(Person, Q_RELOCATABLE_TYPE);There are two things that can go wrong here:
- We forget the macro. Nothing breaks, but we lose the optimization.
- We use the macro on a type that is not trivially relocatable. This is much worse: the code compiles just fine, and then it may misbehave at runtime.
With reflection, we can do something about both.
Detecting trivially relocatable types
Person follows the Rule Of Zero: it doesn't define any copy or move operation, nor a destructor. The compiler generates them for us, and they simply work member by member. So, if relocating each member is just a byte copy, relocating the whole object is a byte copy, too.
This gives us a recipe. A class is automatically trivially relocatable if:
- all of its non-static data members and base classes are trivially relocatable, and none of the bases are virtual; and
- it has no user-provided copy operations, move operations, or destructor.
This isn't a new idea. Barry Revzin explored it in a blog post back in 2024, where he implemented (most of) P2786's type trait using reflection. I am just doing something similar, but on top of Qt's facilities.
Note: the code that follows is a very simplified version of the real one, which also has to deal with references, arrays, and so on.
Let's start with the first half. I'm going to call a type eligible if all of its subobjects are trivially relocatable:
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;
}QTypeInfo is the class template that Q_DECLARE_TYPEINFO specializes. isRelocatableType takes the reflection of a type, plugs it into isRelocatable, and extracts the result. Note the unchecked() access context: we want to look at private members, too.
The second half looks at the special member functions:
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);
});
}Now we can make QTypeInfo use this check by default, and that's it: Person is trivially relocatable, no macro needed!This also works recursively, so a class with a Person data member gets detected as well.
Why user-provided?
The code looks for special member functions that are user-provided, not merely user-declared. A destructor which is = default-ed inside the class is fine.
This is deliberate: it's the same criterion used by trivial copyability, and a trivially copyable type must always be trivially relocatable. It would be absurd if we could memcpy an object in order to copy it, but not in order to relocate it!
For the same reason, I'm not trying to figure out which constructor overload resolution would pick when building an object from an rvalue (maybe a constructor template?). That's what P2786 asked for, and Barry discusses in his post why it can't be precisely implemented using reflection. Trivial copyability doesn't look at that, and neither do I.
Finally, a type with deleted copy and move operations can still be detected as trivially relocatable. I see relocation as an operation of its own, independent from copies and moves.
Checking the types marked by hand
What about a type that follows the Rule Of Five? There we still need the macro: reflection can tell us that there is a user-provided move constructor, but not what it does.
However, we can at least check that the type is eligible! If a class has a data member which isn't trivially relocatable, then marking the class is very likely a mistake. For instance:
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);As we know, std::string is usually not trivially relocatable, because of the Short String Optimization. Today this code compiles without a warning. With a static_assert inside Q_DECLARE_TYPEINFO, we get this instead:
error: static assertion failed: The type Contact is not structurally trivially relocatable("Structurally trivially relocatable" is what the real code calls an eligible type.)
Did it find anything in Qt?
Of course it did! :-)
- A type that was really marked by mistake. One of Qt's own tests had a class with a
std::stringdata member, marked as trivially relocatable. Luckily it was only a test, and it didn't misbehave. - Types that nobody had marked. This was by far the most common case: a class was correctly marked, but the type of one of its data members (or a base class) wasn't. For example,
QArrayDataPointer, the building block ofQStringandQVector, had no marking; neither didQPaintDevice, the base class ofQImage. Here the fix was to add the missing macro. - An empty destructor. A class used by qmake had a destructor defined as
{}, which makes it user-provided. Changing it to= defaultwas enough.
So, apart from that one test, all the classes that we had marked were indeed trivially relocatable: we didn't accidentally mark one that wasn't. But the moment we enforce that all the subobjects must be trivially relocatable as well, the check gets angry, and we need to add the missing markings to their types. Several of these fixes are already in Qt, as they make sense on their own.
The problem: everybody else's types
So, why don't we just turn this on? The difficulties start when a class contains types that don't come from Qt.
Is std::unique_ptr trivially relocatable? In practice, yes, on every Standard Library implementation that Qt supports (as long as its pointer and deleter types are, too). But this isn't "official" in any way, and the detection can't figure it out, because std::unique_ptr has user-provided special member functions. I had to special-case it, together with std::optional.
Those are just the ones used inside Qt. What about std::tuple, std::variant, std::shared_ptr? Containers are even scarier: in debug mode, a Standard Library implementation may store extra data in them, such as pointers back from their iterators. And for some types, like std::atomic, it's questionable whether we want them to be trivially relocatable, given that they can't be copied or moved to begin with.
The same applies to any third-party type you may be using. When the detection says "no", it may be because the type really isn't trivially relocatable, or because nobody has marked it yet. We can't tell the difference! And with the check in place, a correctly marked class could stop compiling just because of one such data member.
Should we then allow the author of a class to force the marking, no matter what its data members say? In the standardization discussions these are called "sharp knife" semantics (the author is always trusted, even when they're wrong), as opposed to "dull knife" semantics (the subobjects have to cooperate). Qt's macro has always been a sharp knife; my experiment turns it into a dull one. Each choice has its own advantages and disadvantages: a sharp knife lets us work around legacy types that nobody has marked, but it also lets us hurt ourselves, like in the std::string example above. I've written more about this in P4197 (it's Question 6), also as a result of this experiment.
Not knowing what a "no" means is also one of the problems that I have with the proposals for Standard C++: they leave unspecified whether a given Standard Library type is trivially relocatable. That's very annoying for adoption.
What if the answer changes?
Suppose that somebody does add the missing marking, and a type goes from "not trivially relocatable" to "trivially relocatable". That's great, right?
Not necessarily: this can be a binary compatibility problem. In the first post we have seen that QVariant stores small objects inside itself only if they're trivially relocatable. Now suppose that a library creates a QVariant containing an object of a type that it considers trivially relocatable, and then passes it to another library, which was built when that type wasn't marked yet. Where is the object stored?
QVariant has been engineered around this problem: it remembers whether it's using its internal storage, so the second library will find the object in the right place. But it's very easy to get this wrong! Imagine a similar type-erased wrapper, with its own small object optimization, which instead checks whether the type is trivially relocatable every time it needs to access the object. If two libraries disagree about the type, one of them will look for the object in the wrong place.
Automatic detection makes this kind of disagreement more likely. Person would be trivially relocatable when compiling in C++26 mode with reflection enabled, and not trivially relocatable in C++20 mode; all it takes is mixing the two in the same application.
Conclusions
In this post we have seen that, using reflection:
- we can automatically detect that simple types, like
Person, are trivially relocatable - we can check that the types marked by hand are at least eligible
- we still need to mark types with user-provided special member functions
- we still don't have a good answer for types that we don't control.
This is just an experiment, and I don't plan to merge it into Qt anytime soon. Still, it's remarkable how little code it takes, and it has already proved useful to find mistakes. If you want to have a look at the real code, the patch is on Gerrit(at the time of this writing, you may need to log in to see it).
In the meanwhile, please keep marking your types. :-)
Thank you for reading!
Overview about all installments:
The post Qt and Trivial Relocation (Part 6) appeared first on KDAB.























