c++ - differences between new char[n] and new (char[n]) -
is there difference between new char[n]
, new (char[n])
?
i have second case in generated code, g++ (4.8.0) gives me
iso c++ not support variable-length array types [-wvla]
this makes me think if these 2 same or not.
new char[n]
means "allocaten
objects of typechar
.- does
new (char[n])
mean "allocate 1 object of typearray of n chars
"? - deleting first clear.
- should delete second
delete
ordelete[]
? - are there other differences should aware of?
- may safely remove parentheses , turn second case first, when other parts of software expect second?
the code generated third party software (and used other parts of software), cannot "use vector instead".
this minimal example:
int main (void) { int n(10); int *arr = new (int[n]); // removing parentheses fixes warning *arr = 0; // no "unused variable" warning return 0; }
the basic issue here c++ not allow array bound [n]
used in type unless n
constant expression. g++ , other compilers allow anyway, it's impossible consistent behavior when start mixing variable-length-arrays , templates.
the apparent exception int* p = new int[n];
works because here [n]
syntactically part of new
expression, not part of type provided new
, , new
"know how" create arrays length determined @ runtime.
// can "constexpr" in c++11: const int c = 12; int main() { int* p1 = new int[c]; int* p2 = new (int[c]); typedef int arrtype[c]; int* p3 = new arrtype; int n = 10; int* p4 = new int[n]; // int* p5 = new (int[n]); // illegal! // typedef int arrtype2[n]; // illegal! // int* p6 = new arrtype2; delete[] p1; delete[] p2; delete[] p3; delete[] p4; }
semantically, though, after final [c]
used convert type array type, new expression cares whether it's dealing array or not. requirements type of expression, whether use new[]
, delete[]
, , on things "when allocated type array", not "when array new syntax used". in example above, initializations of p1
, p2
, , p3
equivalent, , in cases delete[]
correct deallocation form.
the initialization of p4
valid, code p5
, p6
not correct c++. g++ allow them anyway when not using -pedantic
, , analogy i'd expect initializations p4
, p5
, , p6
equivalent. @mm's disassembly supports conclusion.
so yes, should safe improvement remove "extra" parentheses sort of expression. , correct deletion delete[]
type.
Comments
Post a Comment