初始化对象时是否可以放弃放置新的返回值(Is it OK to discard placement new return value when initializing objects)
这个问题来源于这个帖子中的评论部分,并且在那里也得到了答案。 但是,我认为仅仅留在评论部分是非常重要的。 所以我为此做了这个Q&A。
Placement new可用于初始化分配的存储中的对象,例如,
using vec_t = std::vector<int>; auto p = (vec_t*)operator new(sizeof(vec_t)); new(p) vec_t{1, 2, 3}; // initialize a vec_t at p
根据cppref ,
安置新的
如果提供了placement_params,它们将作为附加参数传递给分配函数。 在标准分配函数
void* operator new(std::size_t, void*)
,这样的分配函数被称为“placement new”, 它只是返回其第二个参数不变 。 这用于在分配的存储中构造对象[...]这意味着
new(p) vec_t{1, 2, 3}
只返回p
,而p = new(p) vec_t{1, 2, 3}
看起来是多余的。 忽略返回值真的可以吗?This question originates from the comment section in this thread, and has also got an answer there. However, I think it is too important to be left in the comment section only. So I made this Q&A for it.
Placement new can be used to initialize objects at allocated storage, e.g.,
using vec_t = std::vector<int>; auto p = (vec_t*)operator new(sizeof(vec_t)); new(p) vec_t{1, 2, 3}; // initialize a vec_t at p
According to cppref,
Placement new
If placement_params are provided, they are passed to the allocation function as additional arguments. Such allocation functions are known as "placement new", after the standard allocation function
void* operator new(std::size_t, void*)
, which simply returns its second argument unchanged. This is used to construct objects in allocated storage [...]That means
new(p) vec_t{1, 2, 3}
simply returnsp
, andp = new(p) vec_t{1, 2, 3}
looks redundant. Is it really OK to ignore the return value?
原文:https://stackoverflow.com/questions/49568858