gpt4 book ai didi

c++重载new[],获取请求对象的数量

转载 作者:行者123 更新时间:2023-11-28 06:55:03 24 4
gpt4 key购买 nike

我想重载运算符 new[] 以获取要创建的对象的数量。最好的解决方案是重载 new[],这样在使用 new[] 创建对象时调用者就不需要编写任何额外的代码。即简单地使用:

Myclass objectsArray = new Myclass[5];

示例重载:

class Myclass
{
...
public:
void* operator new[](size_t size)
{
int numberOfObjects = figure out how to get number of objects to be created by this call to new[]
std::cout << "requesting: " << numberOfObjects << " objects" << std::endl;
void * temp = malloc(size) ;
return temp ;
}
...
}

以下示例程序:

Myclass objectsArray = new Myclass[4];

会输出:

requesting: 4 objects

编辑:我只想在 MyClass 中而不是在全局中执行此操作

编辑:我正在使用 GCC 4.8.1 版的 Lubuntu 12.0

编辑:问题的目的:

我使用的是自定义内存池分配器,它不能开箱即用地分配数组。所以我需要知道有多少对象被请求并使用池分配器循环一个一个地创建它们。

最佳答案

您需要定义一个类特定的operator new。这对我有用,但要注意 count/sizeof(MyClass) 表达式中的对齐、派生类大小和分配开销问题:

#include <iostream>
#include <memory>
#include <new>

struct MyClass {
int dummy[8];
void *operator new[](std::size_t count) {
std::cout << "allocating " << count << " bytes, " << ((count-sizeof(void*))/sizeof(MyClass)) << " items\n";
return ::operator new[](count);
}
};

int main() {
auto x = std::make_unique<MyClass[]>(10);
}

(prints: allocating 10 items) 我认为可以通过执行以下操作凭经验确定编译器/stdlib 组合的确切开销:

#include <iostream>
#include <memory>
#include <new>

struct MyClass {
char c;
char d;
virtual ~MyClass() {} // needed for introducing overhead
void *operator new[](std::size_t count) {
void *p = ::operator new[](count);
std::cout << "allocating " << count << " bytes\n";
return p;
}
};

int main() {
for( auto count : { 1, 5, 10, 20 } ) {
std::cout << "allocating " << sizeof(MyClass) << " * " << count << " items\n";
auto x = new MyClass[count];
delete[] x;
}
}

这将在我的机器(和 Coliru 上)打印:

分配 16 * 1 项分配 24 个字节,1 个项目分配 16 * 5 个项目分配 88 个字节,5 个项目分配 16 * 10 个项目分配 168 个字节,10 个项目分配 16 * 20 项分配328字节,20项

所以,我们的count/sizeof(MyClass)(这里)应该是这样的

(count-sizeof(void*))/sizeof(MyClass)

但是YMMV等

最后编辑(我希望如此)

我在 64 位 linux(clang-3.4、clang-3.5 和 gcc-4.8、libstdc++ 和 libc++)上使用以下 how_many_elements 函数取得了成功:

template<class T>
std::size_t how_many_elements(std::size_t bytes) {
return (bytes -
((!std::is_trivially_destructible<T>::value)*sizeof(void*))
) / sizeof(T);
}

所以你的 operator new 变成了这样的:

void *operator new[](std::size_t count) {
std::cout << "allocating " << count << " bytes, " << how_many_elements<MyClass>(count) << " items\n";
return ::operator new[](count);
}

但我没有在 32 位环境中测试它,YMMV 仍然适用。并记住为 MyClass每个 派生类复制 operator new,显然将 MyClass 替换为 MyDerivedClass 或其他...

关于c++重载new[],获取请求对象的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23294937/

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