[英]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::move
或std::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.