Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ placement new keep giving compiling error

Tags:

c++

Try to use placement new but it kept giving me errors. I remember a while ago, it was working. g++ (ver 4.8.4) on 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;
}

Got error

$ 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

Any idea what's wrong?

like image 617
packetie Avatar asked May 02 '26 04:05

packetie


1 Answers

To use placement new, you need to have:

#include <new>

Also, you could just as easily have used:

int main(int argc, char *argv[]) {
    char buf[20];
    strSession *q = new (buf) strSession;
    return 0;
}
like image 123
R Sahu Avatar answered May 04 '26 17:05

R Sahu