<QTypeInfo> Proxy Page

Q_DECLARE_TYPEINFO ( Type , Flags )

宏文档编制

Q_DECLARE_TYPEINFO ( Type , Flags )

You can use this macro to specify information about a custom type Type . With accurate type information, Qt's generic containers can choose appropriate storage methods and algorithms.

Flags can be one of the following:

  • Q_PRIMITIVE_TYPE specifies that Type can be created by zero-initializing its storage, requires no operation to be properly destroyed, and for which memcpy()ing creates a valid independent copy of the object.
  • Q_RELOCATABLE_TYPE specifies that Type has a constructor and/or a destructor but can be moved in memory using memcpy() .
  • Q_MOVABLE_TYPE 如同 Q_RELOCATABLE_TYPE . Prefer to use Q_RELOCATABLE_TYPE in new code. Note: despite the name, this has nothing to do with move constructors or C++ move semantics.
  • Q_COMPLEX_TYPE (the default) specifies that Type has constructors and/or a destructor and that it may not be moved in memory.

Example of a "primitive" type:

struct Point2D
{
    int x;
    int y;
};
Q_DECLARE_TYPEINFO(Point2D, Q_PRIMITIVE_TYPE);
					

An example of a non-POD "primitive" type is QUuid : Even though QUuid has constructors (and therefore isn't POD), every bit pattern still represents a valid object, and memcpy() can be used to create a valid independent copy of a QUuid 对象。

Example of a relocatable type:

class Point2D
{
public:
    Point2D() { data = new int[2]; }
    Point2D(const Point2D &other) { ... }
    ~Point2D() { delete[] data; }
    Point2D &operator=(const Point2D &other) { ... }
    int x() const { return data[0]; }
    int y() const { return data[1]; }
private:
    int *data;
};
Q_DECLARE_TYPEINFO(Point2D, Q_RELOCATABLE_TYPE);
					

Qt will try to detect the class of a type using std::is_trivial_v<T> to identify primitive types and it will require both std::is_trivially_copyable_v<T> and std::is_trivially_destructible_v<T> to identify relocatable types. Use this macro to tune the behavior. For instance many types would be candidates for Q_RELOCATABLE_TYPE despite not being trivially-copyable.