简体   繁体   English

将unique_ptr的向量传递给函数,const引用

[英]Pass a vector of unique_ptr to function, const reference

I usually pass a vector containing raw pointers like this: 我通常会传递一个包含原始指针的向量,如下所示:

someFunc(const std::vector<MyClass*>& classList){..}

I wonder if you can do the same with unique_ptr like this: 我想知道你是否可以像这样对unique_ptr做同样的事情:

 someFunc(const std::vector<std::unique_ptr<MyClass>>& classList){..}

? Does it mean the same thing?, ie read-only. 它是否意味着同样的事情?,即只读。

Yes, you can. 是的你可以。 No, it's doesn't mean the same thing: std::unique_ptr represents a resource that is owned by the pointer. 不,它并不意味着相同的事情: std::unique_ptr表示指针所拥有的资源。 A generic raw pointer can have many other semantics. 通用原始指针可以具有许多其他语义。

With regards to const correctness, accessing the elements of a vector with either iterators or operator[] will yield constant references to std::unique_ptr s. 关于const的正确性,使用迭代器或operator[]访问向量的元素将产生对std::unique_ptr的常量引用。 With a const std::unique_ptr<T> the pointer cannot be reassigned while the T object pointed to can be modified. 使用const std::unique_ptr<T> ,无法重新分配指针,同时可以修改指向的T对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM