TestClass *test = new TestClass();
You using new
which creates a dynamically allocated object (most likely placed on the heap). This type of resource needs to be manually managed by you. By managing, you should use delete
on it after you have done using it.
{
TestClass *test = new TestClass();
// do something
delete test;
}
But for the most of your purposes and intents, you just have to use automatic-storage objects, which frees you the hassle of having to manually manage the object. It would also most likely to have better performance especially in short-lived objects. You should always prefer to use them unless you have a really good reason not to do so.
{
TestClass test;
// do something
}
However, if you need the semantics of dynamically allocated objects or that of pointers, it will always be better to use some mechanism to encapsulate the deletion/freeing of the object/resource for you, which also provides you additional safety especially when you are using exceptions and conditional branches. In your case, it would be better if you use std::unique_ptr
.
{
std::unique_ptr<TestClass> test(new TestClass());
// auto test = std::make_unique<TestClass>(); in C++14
// do something (maybe you want to pass ownership of the pointer)
}
The following is a relevant link to help you decide whether to use automatic storage objects or dynamically allocated objects:
Why should C++ programmers minimize use of 'new'?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…