Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

c++ - Scalar `new T` vs array `new T[1]`

We recently discovery that some code was using new T[1] systematically (properly matched to delete[]), and I'm wondering if this is harmless, or there are some downsides in the generated code (in space or time/performance). Of course, this was hidden behind layers of functions and macros, but that's beside the point.

Logically, it appears to me that both are similar, but are they?

Are compilers allowed to turn this code (using a literal 1, not a variable, but via functions layers, that 1 turns into an argument variable 2 or 3 times before reaching the code using thus new T[n]) into a scalar new T?

Any other considerations/things to know about the difference between these two?

question from:https://stackoverflow.com/questions/58165517/scalar-new-t-vs-array-new-t1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No, the compiler is not allowed to replace new T[1] with new T. operator new and operator new[] (and the corresponding deletes) are replaceable ([basic.stc.dynamic]/2). A user-defined replacement could detect which one is called, so the as-if rule doesn't allow this replacement.

Note: if the compiler could detect that these functions had not been replaced, it could make that change. But there's nothing in the source code that indicates that the compiler-supplied functions are being replaced. The replacement is generally done at link time, simply by linking in the replacement versions (which hide the library-supplied version); that's generally too late for the compiler to know about it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...