【问题标题】: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?如果 C++ 类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,它仍然是 POD 类型吗?
【发布时间】: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


【解决方案1】:

成员函数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>);

【讨论】:

  • 我对 POD 感兴趣的原因是我可以确保我的对象分配在静态内存中。我正在使用 C++11。随着弃用,这是否意味着我被动态分配所困扰?我将运行这些命令。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-08
  • 2014-03-23
  • 1970-01-01
  • 1970-01-01
  • 2019-09-12
  • 1970-01-01
相关资源
最近更新 更多