How to get array size stored in unique_ptr?

牧云@^-^@ 提交于 2020-05-28 18:31:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!