问题
if I do:
std::unique_ptr<int[]> uparr(new int[1984]);
and I pass uparr
to somebody without passing the 1984
to them can they see how many elements it has?
aka is there equivalent of vector's .size() for unique_ptr of array ?
回答1:
No, there isn't. Dynamic arrays are a somewhat defective language feature. You'll essentially always want/need to pass the array length around separately (unless you have some kind of sentinel policy). So you might as well use std::vector
(if you don't mind the extra word for the capacity).
回答2:
No, the information is lost.
If you need to keep track of it, use a vector instead or if you really do not wants the extra services, write a small wrapper around an allocated array. You can for example look at the std::dynarray
proposal that was kicked off the c++1y standard.
来源:https://stackoverflow.com/questions/22662348/how-to-get-array-size-stored-in-unique-ptr