【发布时间】:2020-06-10 16:57:09
【问题描述】:
假设我有以下课程:
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(plain old data)类型吗?
【问题讨论】:
-
FWIW,C++11+ 中没有 POD 这样的东西。有标准的布局和琐碎的类型,你会是前者。
-
对于 POD 对象,编译器将它们分配在静态内存中。标准布局/普通类型中的任何一种是否确保对象将分配在静态内存中?
-
静态内存是什么意思?您是在谈论“堆栈”,还是可执行文件的只读数据部分?
-
您不需要将 POD 对象放在堆栈上。如果您不使用
new创建对象,它将在堆栈中。 -
是的。如果你不使用 new(或智能指针),那么你就没有使用堆。
标签: c++ oop static polymorphism dynamic-memory-allocation