Why is it not possible to access the size of a new[]'d array?

后端 未结 4 1762
误落风尘
误落风尘 2021-02-04 02:56

When you allocate an array using new [], why can\'t you find out the size of that array from the pointer? It must be known at run time, otherwise delete []

4条回答
  •  再見小時候
    2021-02-04 03:41

    Simply put, the C++ standard does not require support for this. It is possible that if you know enough about the internals of your compiler, you can figure out how to access this information, but that would generally be considered bad practice. Note that there may be a difference in memory layout for heap-allocated arrays and stack-allocated arrays.

    Remember that essentially what you are talking about here are C-style arrays, too -- even though new and delete are C++ operators -- and the behavior is inherited from C. If you want a C++ "array" that is sized, you should be using the STL (e.g. std::vector, std::deque).

提交回复
热议问题