mak*_*tie 1 c++ oop smart-pointers
对于此代码,C++中有与智能指针相同的编码?
在External.cpp中:
class ExampleClass {...};
ExampleClass* function()
{
ExampleClass *ptr = new ExampleClass();
ptr->doSomething();
return ptr;
}
Run Code Online (Sandbox Code Playgroud)
在Another.cpp中我想做这样的事情,怎么做?:
ExampleClass *ptr2 = function();
Run Code Online (Sandbox Code Playgroud)
实际上有两个,你可以使用unique_ptr或shared_ptr,看看这里何时使用哪个:我在使用哪种指针?
如果您选择unique_ptr,那么您将得到:
class ExampleClass {...};
std::unique_ptr<ExampleClass> function()
{
std::unique_ptr<ExampleClass> uptr = std::make_unique<ExampleClass>();
uptr->doSomething();
return std::move(uptr);
}
//In Another.cpp
std::unique_ptr<ExampleClass> ptr2 = function();
//you could even store the result in a shared pointer!!
std::shared_ptr<ExampleClass> ptr3 = function();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
120 次 |
| 最近记录: |