如何将std :: unique_ptr传递给函数 [英] How can I pass std::unique_ptr into a function
本文介绍了如何将std :: unique_ptr传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将 std :: unique_ptr
传递给函数?可以说我有以下课程:
How can I pass a std::unique_ptr
into a function? Lets say I have the following class:
class A
{
public:
A(int val)
{
_val = val;
}
int GetVal() { return _val; }
private:
int _val;
};
以下内容无法编译:
void MyFunc(unique_ptr<A> arg)
{
cout << arg->GetVal() << endl;
}
int main(int argc, char* argv[])
{
unique_ptr<A> ptr = unique_ptr<A>(new A(1234));
MyFunc(ptr);
return 0;
}
为什么我不能通过 std :: unique_ptr
转换为函数?当然这是构建的主要目的吗?还是C ++委员会打算让我退回到原始的C型指针并像这样传递它:
Why can I not pass a std::unique_ptr
into a function? Surely this is the primary purpose of the construct? Or did the C++ committee intend for me to fall back to raw C-style pointers and pass it like this:
MyFunc(&(*ptr));
最奇怪的是,为什么这是一种通过的好方法?似乎非常不一致:
And most strangely of all, why is this an OK way of passing it? It seems horribly inconsistent:
MyFunc(unique_ptr<A>(new A(1234)));
推荐答案
这里基本上有两个选择:
There's basically two options here:
void MyFunc(unique_ptr<A> & arg)
{
cout << arg->GetVal() << endl;
}
int main(int argc, char* argv[])
{
unique_ptr<A> ptr = unique_ptr<A>(new A(1234));
MyFunc(ptr);
}
将智能指针移至函数参数中
请注意,在这种情况下,断言将成立!
Move the smart pointer into the function argument
Note that in this case, the assertion will hold!
void MyFunc(unique_ptr<A> arg)
{
cout << arg->GetVal() << endl;
}
int main(int argc, char* argv[])
{
unique_ptr<A> ptr = unique_ptr<A>(new A(1234));
MyFunc(move(ptr));
assert(ptr == nullptr)
}
这篇关于如何将std :: unique_ptr传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文