以 unique_ptr
及其release
方法为例,返回指向托管对象的指针并释放所有权。
有没有办法释放 std::array
的底层数组的所有权?
好的,可以使用 std::unique_ptr
而不是 std::array
,仅此而已。不管怎样,后者有一些不错的特性,例如有时很有用的 size
成员方法。
最佳答案
Is there any way to release the ownership of the underlying array of a std::array?
没有。 std::array
只是原始数组的包装器。它可以重新分配,但这实际上是对数组中所有元素的复制操作。目标数组不指向源数组。
你还应该注意到 std::array
和一个 std::unique_ptr<type[]>
不同之处在于 std::array
大小必须在编译时知道,其中 std::unique_ptr<type[]>
大小可以在运行时设置。全部std::unique_ptr<type[]>
真的是包装一个type * name = new type[some_size]
.
关于c++ - std::array<T, N> 可以释放它的数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38081112/