[英]c++ Passing unique_ptr as a reference to another function
This seens to be basic, but I need some help. 这看起来很基本,但我需要一些帮助。
I have a sample class: 我有一个示例类:
class myClass {
int a;
int b;
}
Then a factory: 然后一家工厂:
class myFactory {
std::unique_ptr<myClass> getInstance()
{
return std::unique_ptr<myClass>(new myClass);
}
}
Then I have several funtions that will receive myClass
by reference: 然后我有几个函数将通过引用接收
myClass
:
doSomething (myClass& instance)
{
instance.a = 1;
instance.b = 2;
}
And the main
code, where I´m stuck: main
代码,我卡住了:
main()
{
myFactory factory;
std::unique_ptr<myClass> instance = factory.getInstance();
doSomething(instance.get()) <--- This is not compiling
}
How do I correctly call the doSomething()
function passing the instance as a reference as expected ? 如何正确调用
doSomething()
函数将实例作为参考传递?
Note that doSomething()
will modify instance data... 请注意,
doSomething()
将修改实例数据...
std::unique_ptr<T>::get
returns the underlying raw pointer, not the pointee. std::unique_ptr<T>::get
返回底层的原始指针,而不是指针。 unique_ptr
provides operator*
for directly getting at the instance. unique_ptr
提供operator*
以直接获取实例。
doSomething(*instance);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.