简体   繁体   English

分配给std :: shared_ptr成员变量

[英]Assigning to a std::shared_ptr member variable

I have a class foo , with a member bar of type std::shared_ptr<int> : 我有一个类foo ,其成员bar的类型为std::shared_ptr<int>

class foo
{
    std::shared_ptr<int> bar;
    /*other stuff here*/
};

In that class I want to assign a new int to bar . 在那个类中,我想为bar分配一个new int But I can't write bar = new int(); 但我不能写bar = new int(); as the pointer does not have a public assignment operator. 因为指针没有公共赋值运算符。

How should I do this? 应该怎么办呢? I could std::move or std::swap but neither of those seem right. 我可以std::movestd::swap但这些都不对。

bar = std::make_shared<int>(); is one way, especially if you like to retain the tractability of an assignment operator. 是一种方式,特别是如果你想保留赋值运算符的易处理性。

You could use reset for this: 您可以使用reset

bar.reset(new int());

This will delete the current contents (if any) and set the internal pointer to that returned by the new expression. 这将delete当前内容(如果有)并将内部指针设置为new表达式返回的内容。

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

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