这里有一个值得注意的video (停止教学C) https://www.youtube.com/watch?v=YnWhqhNdYyk关于 C++ 语言教学中范式的改变。
还有一篇值得注意的博客文章
我有一个梦想 ... http://dev-jungle.blogspot.co.uk/2015/02/i-have-dream-im-dreaming-of-so-called-c.html
我梦想着所谓的 C++ 课程/班级/课程将停止教授(要求)学生使用:...
自从 C++11 作为既定标准以来,我们有动态内存管理 http://en.cppreference.com/w/cpp/memory设施又名智能指针.
即使从早期的标准来看,我们也有 C++ 标准容器库 http://en.cppreference.com/w/cpp/container作为原始数组的良好替代品(分配有new T[]
)(特别是使用std::string http://en.cppreference.com/w/cpp/string/basic_string而不是c风格NUL
终止字符数组)。
问题在bold:
抛开放置位置new
覆盖,是否有任何有效的用例无法使用智能指针或标准容器来实现,而只能使用new
and delete
直接地(当然除了此类容器/智能指针类的实现之外)?
有时候是这样rumored (like here https://www.quora.com/In-C-how-much-slower-is-it-if-at-all-to-use-std-string-instead-of-char* or here https://www.reddit.com/r/cpp/comments/4g63si/modern_c_ethos_suggests_we_avoid_writing_low/)使用new
and delete
手卷可以“更高效”对于某些情况。这些实际上是哪些?这些边缘情况不需要像标准容器或智能指针一样跟踪分配吗?
对于原始 c 风格的固定大小数组几乎相同:有std::array
如今,它允许各种赋值、复制、引用等轻松且语法一致,正如每个人所期望的那样。是否有任何用例可供选择T myArray[N];
c 风格数组优先于std::array<T,N> myArray;
?
关于与第三方库的交互:
假设第 3 方库返回分配的原始指针new
like
MyType* LibApi::CreateNewType() {
return new MyType(someParams);
}
您始终可以将其包装到智能指针以确保delete
叫做:
std::unique_ptr<MyType> foo = LibApi::CreateNewType();
即使 API 要求您调用他们的旧函数来释放资源,例如
void LibApi::FreeMyType(MyType* foo);
您仍然可以提供删除器功能:
std::unique_ptr<MyType, LibApi::FreeMyType> foo = LibApi::CreateNewType();
I'm especially interested in valid "every day" use cases in contrast to academic/educational purpose requirements and restrictions, which aren't covered by the mentioned standard facilities.
That new
and delete
may be used in memory management / garbage collector frameworks or standard container implementation is out of question1.
一大动机...
...提出这个问题是为任何(家庭作业)问题提供一种替代方法,这些问题仅限于使用标题中提到的任何结构,但关于生产就绪代码的严重问题。
这些通常被称为basics内存管理,在我看来这是明显错误/误解为适合初学者讲座和任务。
1)Add.: Regarding that paragraph, this should be a clear indicator that new
and delete
isn't for beginner c++ students, but should be left for the more advanced courses.