C++ 中放置 new VS 显式构造函数调用
最近我遇到了这两种在内存中特定位置创建对象的方法:
1.
void* mem = malloc(sizeof(T));
T* obj = new(mem) T();
2.
T* obj = (T*)malloc(sizeof(T));
*obj = T();
第二种方式有点短...还有其他区别吗? 问候 马特乌什
recently I have come across these two ways of creating an object in a specific place in memory:
1.
void* mem = malloc(sizeof(T));
T* obj = new(mem) T();
2.
T* obj = (T*)malloc(sizeof(T));
*obj = T();
The second way is a bit shorter...are there other differences?
Regards
Mateusz
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第二种方法是错误的,第一种方法是正确的。
您正在包含垃圾数据的 T 实例上调用赋值运算符。赋值运算符期望实例已正确初始化 - 例如,它可能会在赋值之前删除成员变量,这会导致各种有趣的崩溃。请参见例如:
第一种方法将确保调用
Foo::Foo()
- 从而正确初始化Data
。第二种方式将导致delete Data;
,其中Data
指向内存中的某个随机位置。编辑:
您可以通过以下方式测试:
并且:
The second way is wrong, the first is right.
You're invoking the assignment operator on a T instance containg garbage data. The assignment operator expects the instance to have been initialized correctly - It could e.g. delete member variables before assigning, which would cause all sorts of funny crashes. See e.g:
The first way will ensure
Foo::Foo()
is called - thus properly initializingData
. The second way will lead to adelete Data;
whereData
points to some random location in memory.EDIT:
You can test this the following way:
And:
此语句在堆栈上构造一个
T
对象,然后对*obj
进行赋值。它会带来意想不到的后果。另一方面,
该语句按预期通过执行
T()
构造函数方法来初始化指定的内存缓冲区mem
。This statement constructs a
T
object on the stack, and then does an assignment to*obj
. It's wrought with unintended consequences.On the other hand,
This statement initializes a designated memory buffer,
mem
, by executingT()
constructor method, as intended.