【发布时间】:2019-11-13 14:57:33
【问题描述】:
让代码自己解释:
class SomeClass {
private:
std::vector<std::unique_ptr<MyType>> cache;
public:
std::unique_ptr<MyType> getAt1(int i);
MyType* getAt2(int i);
}
std::unique_ptr<MyType> SomeClass::getAt1(int i) {
return std::move(cache[i]);
}
MyType* SomeClass::getAt2(int i) {
return cache[i].get();
}
我想知道 getAt1 是否会使我的向量不一致,或者两种方式都可以。 由于架构缺陷,我真的应该像 getAt1 一样返回。
你有什么意见?
谢谢。
【问题讨论】:
-
这取决于你想要什么。是否要从向量中删除指针?或者您是否想要一个指向与向量中的指针相同的对象的指针?向量是否总是比你从函数返回的指针寿命长?
标签: c++ c++11 smart-pointers unique-ptr