如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗

If a C++ class has dynamic allocation within a class method but has no constructor/destructor or any non-static members, is it still a POD type?

本文关键字:任何非 静态成员 类型 POD 仍然是 析构函数 构造函数 类方法 C++ 如果 动态分配      更新时间:2023-10-16

假设我有以下类:

class A
{
public:
int index;
int init(int type);
}
int A::init(int type)
{
Interface* interface = SelectInterface(type);
int index = interface->get_index(type);
delete interface;
}

然后我有以下界面:

// ----------- INTERFACES -------------- //
class Interface
{
virtual int get_index() = 0;
}
// This is the interface factory
Interface* SelectInterface(int type)
{
if (type == 0)
{ 
return new InterfaceA();
}
else if (type == 1)
{
return new InterfaceB();
}
return null;
}
class InterfaceA :: public Interface
{
InterfaceA();
int get_index();
} 
int InterfaceA::get_index()
{
return 5;
}
class InterfaceB :: public Interface
{
InterfaceB();
int get_index();
} 
int InterfaceB::get_index()
{
return 6;
}

类A没有任何构造函数或析构函数,也没有任何非静态数据成员。然而,类A确实动态地分配对象,然后在类方法中删除它。

A类仍然是POD(纯旧数据(类型吗

成员函数init的作用与否无关。这并不影响A是否是POD类型(在您的示例中是(。

POD是一个老东西,在C++20中不推荐使用,您可能需要检查标准布局。

你可以在你的代码编写中检查

#include <type_traits>
static_assert(std::is_pod<A>::value, "");
static_assert(std::is_standard_layout<A>::value, "");

或C++17以上

#include <type_traits>
static_assert(std::is_pod_v<A>);
static_assert(std::is_standard_layout_v<A>);