fullyanfmotr 2015-12-18 08:35 采纳率: 100%
浏览 1408
已采纳

关于c++的new运算的问题

偶然在网上看到这么一段代码,想问下其中的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();
}

  • 写回答

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指向的内存上调用构造函数

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算