Gir*_*rdi 3 c++ oop pointers c++11
我有一个Base类,具有两个派生类DerivedA和DerivedB和一个返回指针工厂方法Base*.
Base* GetClass(int choice)
{
if (choice == 0)
return new DerivedA();
else if (choice == 1)
return new DerivedB();
throw std::invalid_argument("no no no");
}
Run Code Online (Sandbox Code Playgroud)
无论DerivedA和DerivedB实施的方法,说GetDouble(),这个方法是我感兴趣的关于构建这两种类别的唯一的事情:
double d = GetClass(0)->GetDouble();
Run Code Online (Sandbox Code Playgroud)
我的问题是:当我调用GetClass(0)时,我创建了一个应该被删除的指针.但是,我没有将它实例化为一个对象.我还需要删除它吗?
就像是:
Base* c = GetClass(0);
double d = c->GetDouble();
delete c;
Run Code Online (Sandbox Code Playgroud)
怎么会这样std::unique_ptr?
先感谢您.
通过使用std::unique_ptr,你不会有打电话的麻烦delete.
std::unique_ptr<Base> GetClass(int choice)
{
if (choice == 0)
return std::make_unique<DerivedA>();
else if (choice == 1)
return std::make_unique<DerivedB>();
throw std::invalid_argument("no no no");
}
Run Code Online (Sandbox Code Playgroud)
你现在可以安全地打电话:
double d = GetClass(0)->GetDouble();
Run Code Online (Sandbox Code Playgroud)
这里发生的是:GetClass(0)将返回一个rvalue只会被破坏的东西;.因此,链接的调用,如GetClass(0)->func->func->etc();仍将有GetClass()活着返回的对象,直到;
记住;是C++最强大的功能之一.
double d = GetClass(0)->GetDouble();是内存泄漏.你new在函数中的对象,然后你返回它.您使用返回的对象来调用成员函数,然后丢弃表达式末尾的指针.由于您不再拥有指针,因此可以更长时间地调用delete并释放您抓取的内存.
记住每次拨打new/ new[]需要匹配的呼叫delete/delete[]
既然我们有智能指针,我们可以使用a来解决这个问题std::unique_ptr.指针将为您管理内存,一旦超出范围,它将删除指针.