Home > front end >  Placement New Operator
Placement New Operator

Time:02-14

#include<iostream>
using namespace std;    

int main() {
    int buf[2];
    int *p=new (buf) int(2);
    int *q=new (buf 1) int(6);
    for(int i=0;i<2;i  )
        cout<<buf[i]<<" ";
    return 0;
}

I was trying placement new operator with the following example. For the above code I get the output as:

trial.cpp:7:20: warning: placement new constructing an object of type 'int' and size '4' in a region of type 'int [2]' and size '0' [-Wplacement-new=]
     int *q=new (buf 1) int(6);
2 6

Why am I getting a warning for *q ? From my understanding p and q are 2 pointers pointing to 2 different blocks in buf array. Please correct me if I'm wrong.

CodePudding user response:

This is a GCC bug affecting versions 8 to 10 and fixed in 11, see bug report.

The code is fine, the warning a false-positive.

  • Related