可能正在学习旧的C++标准
我对学习 C++ 很感兴趣,我找到了一本似乎适合我的书。然而,尽管这本书很新,一些读者批评该书的早期版本并没有真正深入研究新的 C++ 标准(如 C++11、C++14、C++17),而是使用了“旧的 C++ 标准”(即 C++11 之前)。
虽然我检查了新版本是否涵盖了 C++11 等的新方面(似乎涵盖了很多),但我不确定学习 C++11 之前的标准是否效率低下?新版本似乎确实涵盖了新的 C++ 标准(C++11 及更高版本),但我们假设它没有。我获得的知识会过时吗?
同样,我是 C++ 的新手,所以我不确定较新的 C++ 标准是否完全改变了语言,可能会删除/更改我将通过这本书(可能已经过时)学习的语言的(整体)部分。我只是想避免学习不再使用或现在使用方式不同(使用更新的标准)的语言的(整体)部分。但是,如果所有新的 C++ 标准所做的都是添加新功能(但不删除/更改旧功能),我认为从书中学习不会成为问题,因为我可以在之后简单地学习更新的功能。
那么,较新的 C++ 标准在哪些方面改变了语言,您会说从一本可能过时的书中学习是一个问题吗?
回答
一些代码在 C++11 中发生了变化,主要变化,IMO,是:
-
“返回”大对象的方法:
- 在 C++11 之前,建议使用输出参数来避免复制:
void MakeVector(std::vector<int>& v) { v.clear(); // fill v; }- 从 C++11 开始,可移动类型不再需要,按值返回是要走的路:
std::vector<int> MakeVector() { std::vector<int> v; // fill v; return v; } -
迭代容器的方法:
- Pre-C++11,它将是索引和迭代器方式的混合:
void Foo(std::vector<int>& v) { for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it) { /* *it ..*/ } for (std::size_t i = 0; i != v.size(); ++i) { /* v[i] ..*/ } }- 从 C++11 开始,它更短(并且最优(
end()只计算一次)):
void Foo(std::vector<int>& v) { for (int& e : v) { /* ..*/ } } -
写类型的方法:
- Pre-C++11,类型应该明确写成:
void Foo(std::vector<int>& v) { std::vector<int>::iterator it = std::find(v.begin(), v.end(), 42); // ... }- 从 C++11 开始,可以推导出类型:
void Foo(std::vector<int>& v) { auto it = std::find(v.begin(), v.end(), 42); // ... } -
创建谓词的方法:
- Pre-C++11,谓词应该作为函数或类在函数之外完成:
bool less_than_42(int i) { return i < 42; } struct less_than_x { less_than_x(int x) : x(x) {} bool operator()(int i) const { return i < x; } int x; }; void Foo(std::vector<int>& v, int x) { std::vector<int>::iterator it1 = std::find_if(v.begin(), v.end(), less_than_42); std::vector<int>::iterator it2 = std::find_if(v.begin(), v.end(), less_than_x(x)); // ... }- 从 C++11 开始,lambda 简化了东西(尽管专用函数可能仍然有助于避免重复 lambda):
void Foo(std::vector<int>& v, int x) { auto it1 = std::find_if(v.begin(), v.end(), [](int e){ return e < 42; }); auto it2 = std::find_if(v.begin(), v.end(), [x](int e){ return e < x; }); // ... }
还有其他更改,但不会使 C++03 编码方式无效。