C++布局新不断给出编译错误

C++ placement new keep giving compiling error

本文关键字:编译 错误 布局 新不断 C++      更新时间:2023-10-16

尝试使用placement new,但它一直给我错误。我记得不久前,它还在工作。g++(版本4.8.4)在Ubuntu 14.04上。

#include <stdio.h>
typedef unsigned int uint;
struct strSession {
    uint   sessionId;
    uint   srcIp;
    uint   dstIp;
};
int main(int argc, char *argv[]) {
    char buf[20];
    strSession *q = (strSession*)&buf[0]; 
    new (q) strSession;
    return 0;
}

收到错误

$ g++ -std=c++11 te.cc `pkg-config --cflags glib-2.0`
te.cc: In function ‘int main(int, char**)’:
te.cc:12:10: error: no matching function for call to ‘operator new(sizetype, strSession*&)’
  new (q) strSession;
          ^
te.cc:12:10: note: candidate is:
<built-in>:0:0: note: void* operator new(long unsigned int)
<built-in>:0:0: note:   candidate expects 1 argument, 2 provided

知道怎么了吗?

要使用放置new,您需要具有:

#include <new>

此外,你也可以很容易地使用:

int main(int argc, char *argv[]) {
    char buf[20];
    strSession *q = new (buf) strSession;
    return 0;
}

要使原始代码正常工作,需要添加

void* operator new( size_t, strSession * p ) { return p; }

在过去,在C++离开贝尔实验室之前,C++有一个特性构造函数可以分配给"this"。操作员的新位置语法被认为是一种改进。