当 malloc 非平凡类型时会发生什么? [英] What will happen when malloc non-trivial type?

查看:50
本文介绍了当 malloc 非平凡类型时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只能通过调用 std::malloc 创建平凡类型的对象(包括数组).

Only objects (including arrays) of trivial type may be created by a call to std::malloc.

我从 http://en.cppreference.com/w/cpp/阅读它types/is_trivial,在 Note 部分下.所以如果我有一个非平凡类型 T,如果我使用 std::malloc(sizeof(T)) 会发生什么?

I read it from http://en.cppreference.com/w/cpp/types/is_trivial, under the Note section. So if I have a non-trivial type T, what will happen if I use std::malloc( sizeof(T) )?

推荐答案

std::malloc 只是旧 C(不是 C++)函数的重命名"malloc(3).

std::malloc is just a "renaming" of old C (not C++) function malloc(3).

所以如果成功,它malloc(sizeof(T))返回一个指针,指向T未初始化内存区域>

So if it succeeds, it malloc(sizeof(T)) returns a pointer to an uninitialized memory zone of the size needed by T

您需要在该内存区域上调用一些 T 的构造函数.您可以为此目的使用 placement new,例如:

You need to call some constructor of T on that memory zone. You could use the placement new for that purpose, e.g:

 void* p = std::malloc(sizeof(T));
 if (!p) throw your_out_of_memory_exception();
 T* ptr = new(p) T(32);  /// placement new, with constructor called with 32

实际上,许多 C++ 实现都有其标准的 ::operator new 做类似的事情.(所以 new 调用 malloc !)

Actually many C++ implementations have their standard ::operator new doing something similar. (So new calls malloc !)

这篇关于当 malloc 非平凡类型时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆