gpt4 book ai didi

c++ - 继承特定于类的内存(取消)分配方法是否会使该类成为非 POD?

转载 作者:太空狗 更新时间:2023-10-29 21:09:47 24 4
gpt4 key购买 nike

如果 C++ POD 类继承了一个除了提供 class-specific memory (de)allocation methods 之外什么都不做的类,那么这是否使 POD 类成为非 POD?

例如,用

struct Myalloc
{
static void* operator new(size_t size);
static void operator delete(void* p);
// ... complete the set of operators
};

struct X : Myalloc {
int y;
double z;
};

X 是 POD 类型吗?不继承Myalloc就是POD类型。

此外,我是否需要为 Myalloc 定义一个虚拟析构函数?我预计不会,因为 Myalloc 不提供数据成员,只提供静态方法。

答案是否取决于所使用的 C++ 标准(例如,C++03、C++11、C++17 等)?我们的代码需要在多个操作系统上编译,因此我们必须编写它们之间支持的最低 C++ 标准,即 C++03 和部分 C++11。

这些问题的原因是我(很不幸)需要让我们自己的类/结构使用我们自己的内存分配例程,并且全局替换默认内存分配例程不是一个好主意。我们的代码库源远流长,其中一些仍然使用 realloc 来扩展保存 POD 值序列的缓冲区的大小。如果当我使 POD 类型继承 Myalloc 时该 POD 类型变为非 POD,那么我预计我将需要显式构造非 POD 值,而不是仅仅为它们分配内存。这将意味着完全重新设计那些古老的代码部分,而不是仅仅用我们自己的版本替换 realloc。我现在无法负担大量额外时间来进行全面重新设计。

最佳答案

您的派生类将不是 POD 类型。 POD 类型在 C++03 中定义为

9(4): "A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-define copy operator and no user-defined destructor. Similarly a POD-union is an aggregate union that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-define copy operator and no user-defined destructor.

因为它被定义为聚合,如果我们看一下它是如何定义的,我们就有

8.5.1(1): "An aggregate is an array or class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10) and no virtual functions (10.3)."

我们可以看到它明确地不允许有一个基类。这意味着您不能拥有从其他类型派生的 Pod 类型,无论该类型是否为 POD。 C++11 没有改变这一点,因为聚合仍然不能有基类。

关于c++ - 继承特定于类的内存(取消)分配方法是否会使该类成为非 POD?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57220533/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com