<QTypeInfo>

用于指定自定义类型信息的宏。更多内容...

Header: #include <QTypeInfo>

宏

Q_DECLARE_TYPEINFO(Type, Flags)

详细说明

宏文档

Q_DECLARE_TYPEINFO(Type, Flags)

您可以使用此宏来指定自定义类型Type 的相关信息。有了准确的类型信息,Qt的泛型容器就能选择合适的存储方法和算法。

Flags 可以是以下选项之一:

  • Q_PRIMITIVE_TYPE 指定Type 无需执行任何操作即可被正确销毁,并且可以使用 memcpy() 创建该对象的有效独立副本。
  • Q_RELOCATABLE_TYPE 指定Type 具有构造函数和/或析构函数,但仍可通过使用memcpy() 在内存中重新定位该对象。
  • Q_MOVABLE_TYPE 与 `Q_RELOCATABLE_TYPE` 相同。在新代码中建议使用 `Q_RELOCATABLE_TYPE `。注意:尽管名称如此,但这与移动构造函数或 C++ 移动语义无关。
  • Q_COMPLEX_TYPE (默认值)指定Type 具有构造函数和/或析构函数,且不能在内存中移动。

“原始”类型的示例:

struct Point3D
{
    int x;
    int y;
    int z;
};

Q_DECLARE_TYPEINFO(Point3D, Q_PRIMITIVE_TYPE);

QUuid 是一个非 POD “基本”类型的示例:尽管QUuid 具有构造函数(因此不属于 POD),但每个位模式仍代表一个有效的对象,并且可以使用 memcpy() 创建QUuid 对象的一个有效的独立副本。

可重定位类型的示例:

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 将尝试使用标准 C++ 类型特征来检测类型所属的类;可使用此宏来调整该行为。例如,尽管许多类型并非可平凡复制的,但它们仍可能是 Q_RELOCATABLE_TYPE 的候选对象。

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.