Czy można bezpiecznie przekazywać parametry funkcji, takie jak getAName(getA().get())
? getA()
zwraca obiekt unique_ptr<A>
.C++: Czy można bezpiecznie przekazywać argumenty takie jak unique_ptr :: get() do funkcji
Testuję z całym kodem poniżej na VS 2010, to działa. Ale chciałbym się upewnić, czy jest to standard C++, czy jest bezpieczny z innymi kompilatorami C++?
#include "stdafx.h"
#include <memory>
#include <iostream>
using namespace std;
class A
{
public:
A(){ cout<<"A()"<<endl;}
~A(){ cout<<"~A()"<<endl;}
string name() { return "A"; }
};
std::unique_ptr<A> getA()
{
return std::unique_ptr<A>(new A());;
}
void getAName(A* a)
{
if(a)
{
cout << a->name().c_str() << endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
getAName(getA().get());
return 0;
}
Wyjścia w konsoli to:
A()
A
~()
Jest to konieczne, aby kod jak poniżej bezpieczny dla wszystkich kompilatorów?
unique_ptr<A> a = getA();
getAName(a.get());
c_str() nie jest wymagane, jeśli używasz cout – Kapil