在C ++ 11后的现代C ++中使用原始指针 [英] Use of raw pointers in modern C++ post C++11

查看:99
本文介绍了在C ++ 11后的现代C ++中使用原始指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于大多数体面的编译器现在都很好地支持C ++ 11标准,因此在2014年使用原始指针的主要原因有哪些?

我确定了几种情况:

  1. 您正在扩展旧代码库,该代码库大量使用了原始指针,并且您希望保持样式的一致性.

  2. 您正在使用仅导出原始指针的库,但我想您仍然可以使用强制转换.

  3. 您想利用指针的功能来提供多个间接级别. (我不太了解C ++ 11,无法知道是否可以使用智能指针或其他一些技术来实现.)

您认为哪些其他情况适合使用指针?

今天,您甚至会建议您全面了解指针吗?

我可以想像一下您有一个静态分配的数组,并且想要使用原始指针在高性能代码中对其进行迭代的情况.仍然没有错.

您的#1是真的.

您的#2可能是不对的:如果您使用强制转换"将第三方库拥有的原始指针转换为智能指针(暗示本地所有权),则说明出现了严重错误.

从技术上讲,您的#3是真实的,但请尽可能避免这种情况.

当今不建议使用的不是,它正在使用指向您自己的动态分配的内存的原始指针.也就是说,建议是避免在没有智能指针的情况下使用new(其必然结果是您不需要delete).

What are some of the main reasons to use raw pointers in 2014, given that the C++11 standard is now well supported by most decent compilers?

I identified a couple of scenarios :

  1. You are extending a legacy codebase that makes heavy use of raw pointers, and you would like to maintain consistency in style.

  2. You are using a library that only exports raw pointers, but I guess you could still make use of casts.

  3. You want to exploit pointers's capability to provide multiple levels of indirection. (I do not know C++11 well enough to know if this can be achieved using smart pointers, or using some other techniques.)

What other scenarios do you think are appropriate for use of pointers?

Would you even recommending learning about pointers in general, today?

解决方案

I can imagine circumstances where you have a statically-allocated array and you want to use a raw pointer to iterate through it in high-performance code. There's still nothing wrong with this.

Your #1 is true.

Your #2 is possibly not right: if you're "making use of casts" to transform raw pointers owned by a third-party library, into smart pointers (implying local ownership) then something has gone horribly wrong.

Your #3 is technically true but avoid this whenever you can.

What is not recommended nowadays is playing with raw pointers to your own, dynamically-allocated memory. That is, the advice is to avoid new without smart pointers (and the corollary is that you shouldn't need delete).

这篇关于在C ++ 11后的现代C ++中使用原始指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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