在您添加删除之前,它们是不同的。
您的示例过于琐碎,但析构函数实际上可能包含执行某些实际工作的代码。这被称为 RAII。
所以添加删除。确保即使在传播异常时也会发生这种情况。
Pixel* p = NULL; // Must do this. Otherwise new may throw and then
// you would be attempting to delete an invalid pointer.
try
{
p = new Pixel();
p->x = 2;
p->y = 5;
// Do Work
delete p;
}
catch(...)
{
delete p;
throw;
}
如果您选择了更有趣的东西,例如文件(这是需要关闭的资源)。然后用你需要的指针在 Java 中正确地执行此操作。
File file;
try
{
file = new File("Plop");
// Do work with file.
}
finally
{
try
{
file.close(); // Make sure the file handle is closed.
// Oherwise the resource will be leaked until
// eventual Garbage collection.
}
catch(Exception e) {};// Need the extra try catch to catch and discard
// Irrelevant exceptions.
// Note it is bad practice to allow exceptions to escape a finally block.
// If they do and there is already an exception propagating you loose the
// the original exception, which probably has more relevant information
// about the problem.
}
C++ 中的相同代码
std::fstream file("Plop");
// Do work with file.
// Destructor automatically closes file and discards irrelevant exceptions.
尽管人们提到了速度(因为在堆上查找/分配内存)。就我个人而言,这对我来说不是决定因素(分配器非常快,并且已经针对不断创建/销毁的小对象的 C++ 使用进行了优化)。
对我来说,主要原因是对象寿命。本地定义的对象具有非常具体且定义明确的生命周期,并且保证在最后调用析构函数(因此可能具有特定的副作用)。另一方面,指针控制具有动态生命周期的资源。
C++ 和 Java 的主要区别在于:
谁拥有指针的概念。所有者有责任在适当的时候删除该对象。这就是为什么您很少在实际程序中看到像这样的原始指针(因为没有与原始指针关联的所有权信息)。相反,指针通常包装在智能指针中。智能指针定义了谁拥有内存以及谁负责清理它的语义。
例子是:
std::auto_ptr<Pixel> p(new Pixel);
// An auto_ptr has move semantics.
// When you pass an auto_ptr to a method you are saying here take this. You own it.
// Delete it when you are finished. If the receiver takes ownership it usually saves
// it in another auto_ptr and the destructor does the actual dirty work of the delete.
// If the receiver does not take ownership it is usually deleted.
std::tr1::shared_ptr<Pixel> p(new Pixel); // aka boost::shared_ptr
// A shared ptr has shared ownership.
// This means it can have multiple owners each using the object simultaneously.
// As each owner finished with it the shared_ptr decrements the ref count and
// when it reaches zero the objects is destroyed.
boost::scoped_ptr<Pixel> p(new Pixel);
// Makes it act like a normal stack variable.
// Ownership is not transferable.
还有其他的。