C++中经常被误解的概念有哪些?
C++中经常被误解的概念有哪些?
C++不是带有类的C语言!
而且也没有叫做C/C++的语言。从那里开始,一切都会走下坡路。
C++确实具有自动资源管理。(Most people who claim that C++ does not have memory management try to use new and delete way too much, not realising that if they allowed C++ to manage the resource themselves, the task gets much easier).
例如:(使用虚构的API创建)
// C++
void DoSomething()
{
File file("/tmp/dosomething", "rb");
... do stuff with file...
// file is automatically free'ed and closed.
}
// C#
public void DoSomething()
{
File file = new File("/tmp/dosomething", "rb");
... do stuff with file...
// file is NOT automatically closed.
// What if the caller calls DoSomething() in a tight loop?
// C# requires you to be aware of the implementation of the File class
// and forces you to accommodate, thus voiding implementation-hiding
// principles.
// Approaches may include:
// 1) Utilizing the IDisposable pattern.
// 2) Utilizing try-finally guards, which quickly gets messy.
// 3) The nagging doubt that you've forgotten something /somewhere/ in your
// 1 million loc project.
// 4) The realization that point #3 can not be fixed by fixing the File
// class.
}
auto
关键字是(栈分配的)局部变量的默认存储类。使用new
关键字标记堆分配时,则需要手动进行资源管理。然而,程序员经常滥用new
关键字导致内存泄漏,然后声称C++没有自动资源管理,实际上是他们禁用了自动资源管理。 - Lie Ryan自由函数并不差只因为它们不在类中 C++ 不仅仅是一门面向对象的语言,而是建立在一整套技术之上。
我经常听到人们说自由函数(那些在命名空间和全局命名空间中的函数)是“C 时代的遗物”,应该避免使用。相反,自由函数允许将函数与特定类解耦,并允许重用功能。如果函数不需要访问实现细节,则建议使用自由函数而不是成员函数 - 因为这将消除更改类的实现时可能引起的级联更改等其他优势。
这也反映在语言本身:在 C++0x
中(即将发布的下一个版本),基于范围的 for 循环将基于自由函数调用。它将通过调用自由函数 begin
和 end
来获取 begin / end 迭代器。
赋值和初始化的区别:
string s = "foo"; // initialisation
s = "bar"; // assignment
初始化始终使用构造函数,赋值始终使用operator=运算符
按降序排列:
有趣的是,很少有人知道虚函数的全部细节,但似乎仍能顺利完成工作。
delete
指针(除非你自己正在实现智能指针)。因此,我认为这本身就是一个误解。 - Billy ONealstd::string
并不是设计糟糕 -- 它只是没有将大部分功能作为其签名的一部分。因此,应该使用 STL 风格的算法来处理它。许多 C++ 程序员认为 std::string
是 Java 或 C# 字符串的劣质版本,而不是完整的 STL 容器。 - Billy ONealstd::string
设计得不好? - Destructor过度使用与多态无关的继承。大多数情况下,除非您真正使用运行时多态性,否则组合或静态多态性(即模板)更好。
静态关键字根据使用位置的不同,可以有三种不同的含义。
数组不是指针
它们是不同的。因此,&array
不是指向指针的指针,而是指向数组的指针。在我看来,这是 C 和 C++ 中最被误解的概念。你必须访问所有那些告诉你要将二维数组作为 type**
传递的 SO 回答!
以下是一些内容:
const
和实际const
之间的区别。何时使用mutable
关键字。致谢:感谢spoulson纠正我的错误。
编辑:
以下是更多内容: