偶然在网上看到这么一段代码,想问下其中的new (pv)Solution()是什么用法
class Solution {
public:
int a;
char c;
static int sb;
};
Solution x;
void main()
{
Solution s;
void *pv = operator new(sizeof(Solution));
Solution *ps = new (pv)Solution(); //这是什么用法?
Solution *ps2 = new Solution();
}
关于c++的new运算的问题
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
3条回答 默认 最新
fullyanfmotr 2015-12-18 12:02关注谢谢各位回答,在c++primer找到答案了
new (place_address) type
new (place_address) type (initializers)
new (place_address) type [size]
new (place_address) type [size] { braced initializer list }
where place_address must be a pointer and the initializers provide (a possibly empty)
comma-separated list of initializers to use to construct the newly allocated object.
When called with an address and no other arguments, placement new uses
operator new(size_t, void*) to “allocate” its memory. This is the version of
operator new that we are not allowed to redefine (§ 19.1.1, p. 822). This function
does not allocate any memory; it simply returns its pointer argument. The overall new
expression then finishes its work by initializing an object at the given address. In
effect, placement new allows us to construct an object at a specific, preallocated
memory address.
效果就是在pv指向的内存上调用构造函数本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报