C++ placement new 不断给出编译错误
C++ placement new keep giving compiling error
尝试使用 placement new 但它一直给我错误。我记得不久前,它正在工作。 Ubuntu 14.04 上的 g++(版本 4.8.4)。
#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'。运营商新安置
语法被认为是一种改进。
尝试使用 placement new 但它一直给我错误。我记得不久前,它正在工作。 Ubuntu 14.04 上的 g++(版本 4.8.4)。
#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'。运营商新安置 语法被认为是一种改进。