use*_*947 1 c++ pointers reference shared-ptr c++11
class a
{
private:
std::shared_ptr <std::string> sptr;
public:
void set(std::string & ref)
{
sptr = &ref; //error
}
};
Run Code Online (Sandbox Code Playgroud)
解决方案是什么?我需要保持引用作为参数,我需要私有指针为shared_ptr.
要为共享指针分配新的原始指针并使共享指针获得所有权,请使用成员函数reset:
std::shared_ptr<Foo> p;
p.reset(new Foo);
Run Code Online (Sandbox Code Playgroud)
共享指针共享对象的所有权,因此几乎不可能sptr在任意引用上明智地拥有您的共享所有权.(例如sptr.reset(&ref),几乎肯定是完全错误的.)适当的做法是制作字符串的新副本,即sptr.reset(new std::string(ref))或者更好:
sptr = std::make_shared<std::string>(ref);
Run Code Online (Sandbox Code Playgroud)