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;
};
The following does not compile:
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;
}
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)));
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…