如何为std :: vector创建shared_ptr? [英] How can I create a shared_ptr to a std::vector?
问题描述
我需要为std :: vector创建一个shared_ptr,正确的语法是什么?
I need to create a shared_ptr to a std::vector, what is the correct syntax?
std::vector<uint8_t> mVector;
shared_ptr<std::vector<uint8_t>> mSharedPtr = &mVector;
上面的代码无法编译。
谢谢。
推荐答案
您要尝试的是让智能指针管理堆栈对象。这是行不通的,因为堆栈对象在超出范围时会自行杀死。智能指针不能阻止它执行此操作。
What you are trying to do is to let a smart pointer manage a stack object. This doesn't work, as the stack object is going to kill itself when it goes out of scope. The smart pointer can't prevent it from doing this.
std::shared_ptr<std::vector<uint8_t> > sp;
{
std::vector<uint8_t> mVector;
sp=std::shared_ptr<std::vector<uint8_t> >(&mVector);
}
sp->empty(); // dangling reference, as mVector is already destroyed
三种选择:
Three alternatives:
(1)初始化向量,并通过以下方式对其进行管理 shared_ptr
:
(1) Initialize the vector and let it manage by the shared_ptr
:
auto mSharedPtr = std::make_shared<std::vector<uint8_t> >(/* vector constructor arguments*/);
(2)管理向量的副本(通过调用向量副本构造函数):
(2) Manage a copy of the vector (by invoking the vector copy constructor):
std::vector<uint8_t> mVector;
auto mSharedPtr = std::make_shared<std::vector<uint8_t> >(mVector);
(3)移动向量(通过调用向量移动构造函数):
(3) Move the vector (by invoking the vector move constructor):
std::vector<uint8_t> mVector;
auto mSharedPtr = std::make_shared<std::vector<uint8_t> >(std::move(mVector));
//don't use mVector anymore.
这篇关于如何为std :: vector创建shared_ptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!