这种使用放置 new[] 有什么问题?做
What's wrong with this use of placement new[]? do
考虑下面的程序。它是由一个复杂的情况简化而来的。它在删除以前分配的内存时失败,除非我删除Obj类中的虚拟析构函数。我不明白为什么程序输出的两个地址不同,除非存在虚析构函数。
// GCC 4.4
#include <iostream>
using namespace std;
class Arena {
public:
void* alloc(size_t s) {
char* p = new char[s];
cout << "Allocated memory address starts at: " << (void*)p << 'n';
return p;
}
void free(void* p) {
cout << "The memory to be deallocated starts at: " << p << 'n';
delete [] static_cast<char*> (p); // the program fails here
}
};
struct Obj {
void* operator new[](size_t s, Arena& a) {
return a.alloc(s);
}
virtual ~Obj() {} // if I remove this everything works as expected
void destroy(size_t n, Arena* a) {
for (size_t i = 0; i < n; i++)
this[n - i - 1].~Obj();
if (a)
a->free(this);
}
};
int main(int argc, char** argv) {
Arena a;
Obj* p = new(a) Obj[5]();
p->destroy(5, &a);
return 0;
}
这是我的实现中存在虚析构函数时程序的输出:
分配的内存地址从:0x8895008开始要释放的内存从以下位置开始:0x889500c
RUN FAILED (exit value 1)
请不要问程序应该做什么。正如我所说,它来自一个更复杂的情况,Arena是各种类型内存的接口。在这个例子中,内存只是从堆中分配和释放。
this
不是new
在char* p = new char[s];
行返回的指针,可以看到这里的s
的大小大于5个Obj
实例。差异(应该是sizeof (std::size_t)
)在额外的内存中,包含数组的长度5,紧接this
中包含的地址。
http://sourcery.mentor.com/public/cxx-abi/abi.html array-cookies
2.7 Array Operator new Cookies
当使用new操作符创建新数组时,通常存储cookie以记住分配的长度(数组元素的数量),以便可以正确地释放。
专:如果数组元素类型T有一个普通的析构函数(12.4 [class.dtor])和通常的(array)释放函数(3.7.3.2 [basic.stc.dynamic.deallocation])函数不接受两个参数,则不需要cookie。
因此,析构函数的虚性是无关紧要的,重要的是析构函数是非平凡的,您可以通过删除析构函数前面的关键字virtual
来轻松检查,并观察程序崩溃。
根据chills的回答,如果你想让它"安全":
#include <type_traits>
a->free(this - (std::has_trivial_destructor<Obj>::value ? 1 : 0));
- 警告处理为错误这里有什么问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 违反const正确性:我应该现实地期待什么问题
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 我的逻辑反转字符串中的元音有什么问题?
- 需要以下代码的帮助,下面的代码有什么问题
- 常量公共成员有什么问题?
- 以下代码中的函数模板有什么问题?
- 这个返回元素位置的基于循环的函数有什么问题?
- creat_list2功能有什么问题?
- 格式说明符C++有什么问题
- 任何人都可以告诉我我的 C++ 代码出了什么问题?
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 我的堆栈和库存清单程序的结构有什么问题?
- 此工厂功能有什么问题?
- 以下 C++ 代码有什么问题?
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- reinterpret_cast,只读访问,简单的可复制类型,会出什么问题?
- 它解决了什么问题,对于非真空初始化,生命周期在初始化之前就开始了