C ++(14)和手动内存管理 [英] C++ (14) and manual memory management

查看:124
本文介绍了C ++(14)和手动内存管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚收到一则评论,例如

I have just received a comment, like


问题是手动内存管理。 delete 在用户代码中没有位置,从C ++ 14开始, new

The problem is the manual memory management. delete has no place in user code, and as of C++14, nor has new

有人可以解释为什么吗?

Can someone please explain me why?

推荐答案


警告:我坚持这个答案,因为我认为它提出了一个最佳实践,将提高〜95%的C ++代码 - 可能更多。

Caveat: I stand by this answer since I think it presents a best practice which will improve ~95% of C++ code – probably even more. That said, please read the full comments for a discussion of some important caveats.

因为这是我的一个重要注意事项,所以请阅读评论,这里是我的演示文稿解释这一点。

Since it was my comment, here’s my presentation explaining this.

简而言之:


[Raw]指针
必须。不。拥有。
资源。

这是容易出错和不必要的,因为我们有更好的方式来管理资源,更少的错误,更短的,更可读的代码和更高的置信度。

It’s error-prone and unnecessary because we have better ways of managing resources which result in less errors, shorter, more readable code and higher confidence in the correctness of the code. In economic terms: they cost less.

更具体地说,我的意见是:

To be more specific with regards to the comment I made:

从C ++ 11(现在两年,并在相关部分,由所有现代编译器),手动删除内存是完全不必要的(除非你写非常低级内存处理代码),因为你总是可以使用智能指针,通常甚至不需要它们(见演示文稿)。但是,当实例化一个新的 std :: unique_ptr 时,C ++ 11仍然需要使用 new 。在C ++ 14中,函数 std :: make_unique 不需要使用 new

As of C++11 (out now for two years and implemented, in the relevant parts, by all modern compilers), manually deleting memory is completely unnecessary (unless you write very low-level memory handling code) because you can always use smart pointers instead, and usually don’t even need them (see the presentation). However, C++11 still requires you to use new when instantiating a new std::unique_ptr. In C++14, the function std::make_unique makes this usage of new unnecessary. Consequently, it’s not needed any more either.

在代码中仍然可以放置一个放置位置 - new 但是这是(a)与正常 new 完全不同的情况,尽管语法是相似的,并且(b)在大多数情况下可以使用 allocator :: construct 函数。

There is still arguably a place for placement-new in code, but this is (a) an entirely different case from normal new, even though the syntax is similar, and (b) can be replaced in most cases by using the allocator::construct function.

James指出了这个规则的一个例外,我真的忘记了:当一个对象管理自己的生命时。我会在一个肢体出去,说这在大多数情况下不是一个常见的成语,因为对象生命时间可以总是被外部管理。然而,在某些应用程序中,将对象从代码的其余部分解耦并让它自己管理可能是有益的。在这种情况下,您需要动态分配对象并使用 delete this 解除分配。

James has pointed out an exception to this rule which I had honestly forgotten about: when an object manages its own life-time. I’ll go out on a limb and say that this is not a common idiom in most scenarios, because object life-time can always be managed externally. However, in certain applications it may be beneficial to decouple the object from the rest of the code and let it manage itself. In that case, you need to dynamically allocate the object and deallocate it using delete this.

这篇关于C ++(14)和手动内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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