C ++对象实例化 [英] C++ Object Instantiation

查看:547
本文介绍了C ++对象实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个C程序员试图理解C ++。许多教程使用以下代码段来演示对象实例化:

I'm a C programmer trying to understand C++. Many tutorials demonstrate object instantiation using a snippet such as:

Dog* sparky = new Dog();

这意味着以后你会这样做:

which implies that later on you'll do:

delete sparky;

这很有意义。现在,在动态内存分配不必要的情况下,是否有任何理由使用上述代替

which makes sense. Now, in the case when dynamic memory allocation is unnecessary, is there any reason to use the above instead of

Dog sparky;

并且一旦sparky超出范围,调用析构函数?

and let the destructor be called once sparky goes out of scope?

谢谢!

推荐答案

相反,你应该总是喜欢堆栈分配,一个经验法则,你不应该在你的用户代码中有新的/删除。

On the contrary, you should always prefer stack allocations, to the extent that as a rule of thumb, you should never have new/delete in your user code.

正如你所说,当变量被声明在栈上时,它的析构函数被自动调用当它超出范围时,这是你跟踪资源生命周期和避免泄漏的主要工具。

As you say, when the variable is declared on the stack, its destructor is automatically called when it goes out of scope, which is your main tool for tracking resource lifetime and avoiding leaks.

因此,一般来说,每次你需要分配一个资源,内存(通过调用new),文件句柄,套接字或其他任何东西,将它包装在一个类中,其中构造函数获取资源,析构函数释放它。然后,您可以在堆栈上创建该类型的对象,并且保证您的资源在超出范围时可以释放。

So in general, every time you need to allocate a resource, whether it's memory (by calling new), file handles, sockets or anything else, wrap it in a class where the constructor acquires the resource, and the destructor releases it. Then you can create an object of that type on the stack, and you're guaranteed that your resource gets freed when it goes out of scope. That way you don't have to track your new/delete pairs everywhere to ensure you avoid memory leaks.

这个成语的最常见的名字是RAII

The most common name for this idiom is RAII

同时查看智能指针类,用于将结果指针在罕见的情况下,你必须在新的外部分配一个专用的RAII对象。而是将指针传递给智能指针,然后跟踪其生命周期,例如通过引用计数,并在最后一个引用超出范围时调用析构函数。标准库对于简单的基于作用域的管理具有 std :: unique_ptr ,并且引用计数 std :: shared_ptr 以实现共享所有权。

Also look into smart pointer classes which are used to wrap the resulting pointers on the rare cases when you do have to allocate something with new outside a dedicated RAII object. You instead pass the pointer to a smart pointer, which then tracks its lifetime, for example by reference counting, and calls the destructor when the last reference goes out of scope. The standard library has std::unique_ptr for simple scope-based management, and std::shared_ptr which does reference counting to implement shared ownership.


许多教程使用代码片段显示对象
实例化...

Many tutorials demonstrate object instantiation using a snippet such as ...

所以你发现的是,大多数教程都吸。 ;)
大多数教程教会你糟糕的C ++实践,包括调用new / delete在不必要时创建变量,并让您难以跟踪分配的生命周期。

So what you've discovered is that most tutorials suck. ;) Most tutorials teach you lousy C++ practices, including calling new/delete to create variables when it's not necessary, and giving you a hard time tracking lifetime of your allocations.

这篇关于C ++对象实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆