如果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?
假设我有以下类:
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>);
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 如何在C++中使用非静态成员函数作为回调函数
- C++:是否可以使用非静态成员变量模板?
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 为什么传递非静态成员函数会导致编译错误?
- 非静态成员失败的线程调用函数
- 处理类内的回调时,必须调用对非静态成员函数的引用
- 非静态成员函数的 decltype 格式不正确吗?
- std::异步与非静态成员函数
- C++无效使用非静态成员函数?
- 静态 CPP 中的非静态成员
- 非静态成员引用必须相对于特定对象
- C++:如何返回指向非静态成员函数的指针?
- 在 stream_descriptor::async_wait 中无效使用非静态成员函数
- C++ - 非静态 void* 成员,指向具有相同地址但不同值的不同对象的另一个非静态成员
- 无法在clang Linux中分配非静态成员函数,但我可以在Visual Studio Windows中分配
- 初始化在类类型 #define 中定义的非静态成员数组,不带默认 ctor
- 错误:无效使用非静态成员函数"int test::hotplug_callback(libusb_contex
- 使用 vector.sort() 的非静态成员函数无效使用
- 指向非静态成员函数的 C++ 指针