Home > database >  May this kind of rewrite of placement new compile?
May this kind of rewrite of placement new compile?

Time:07-06

Background

I am cleaning up a legacy codebase by applying a coding guideline for the new statement.

There is code like auto x = new(ClassName); that I rewrite to auto x = new ClassName();. It's quite obvious that this is not a placement new and I don't need to think about it.

However, there's also code like auto x = new(ClassName)(argument); which looks much like a placement new. For now I blindly rewrote such code to auto x = new ClassName(argument); as well.

Question

Might there be a case where a real placement new like auto x = new(placement-params)(Type); is rewritten as auto x = new placement-params(Type); and it still compiles but changes the meaning of the program?

CodePudding user response:

placement-params is not a type, it is a value.

Consider this code with a placement new:

int* buf = new int;
int* a = new(buf)(int);

If we remove parenthesis around buf, the compiler can easily detect buf is not a type.

int* a = new buf(int); // compile error

Even if we create a type named buf, by the name lookup rules, the name in the inner scope is found first:

class buf {         // found second
    buf(int) {}
};

int main() {
    int *buf = new int;  // found first
    int* a = new buf(int); // compile error
    return 0;
}

According to this answer, when type and value are in a same scope, the value is found first. For example:

class buf {         // found second
    buf(int) {}
};
int *buf = new int;  // found first

int main() {
    int *a = new buf(int);  // compile error
    return 0;
}
  • Related