arj*_*soh 4 c++ memory-management new-operator
我在处理C++程序中的内存方面没有经验,所以在这种情况下我想要一条建议:
我想new Object在一个类中创建一个函数,这个函数在程序结束之前是必不可少的.就我而言,如果我使用运算符new,我有时应该删除它.考虑到它必须在一个类中初始化,我何时以及如何最终删除它?
我建议智能指针成语
#include <memory>
struct X
{
void foo() { }
};
std::share_ptr<X> makeX() // could also be a class member of course
{
return std::make_shared<X>();
}
int main()
{
std::share_ptr<X> stayaround = makeX();
// can just be used like an ordinary pointer:
stayaround->foo();
// auto-deletes <sup>1</sup>
}
Run Code Online (Sandbox Code Playgroud)
如果指针确实是一个静态变量,你可以替换a unique_ptr(它的工作方式类似,但在赋值时传递所有权;这意味着指针不必保持引用计数)
注意要了解有关C++智能指针的更多信息,请参阅智能指针(boost)
注意如果您没有TR1/C++ 0x支持,则可以使用Boost Smartpointer
1除非您泄漏 shared_ptr本身的副本; 这将是一些奇怪的使用智能指针以前看不见:)
编辑:使用某种智能指针通常是一个好主意,但我相信对 C++ 中的手动内存管理有深入的了解仍然很重要。
如果您希望类中的对象一直持续到程序结束,只需将其设为成员变量即可。从你所说的来看,没有什么建议你需要在这里使用newor delete,只需将其设为自动变量即可。如果您确实想使用newanddelete进行练习,您应该阅读类的构造函数和析构函数new(您可以并且将会在类之外使用and delete,但我试图使其与您的问题相关)。这是我之前准备的:
class Foo
{
public:
Foo(); // Default constructor.
~Foo(); // Destructor.
private:
int *member;
}
Foo::Foo() // Default constructor definition.
{
member = new int; // Creating a new int on the heap.
}
Foo::~Foo() // Destructor.
{
delete member; // Free up the memory that was allocated in the constructor.
}
Run Code Online (Sandbox Code Playgroud)
这是一个简单的例子,但希望对您有所帮助。请注意,只有当对象还活着时,变量才会持续存在。如果对象被销毁或超出范围,将调用析构函数并释放内存。
| 归档时间: |
|
| 查看次数: |
3059 次 |
| 最近记录: |