作为使用的记录,方便后续的查询,欢迎大家一起来完善。我会定期根据使用频率调整顺序。
大部分说明,都会出自cppreference网站
- emplace_back
这个函数是为了提高一种情况下的,入栈效率存在的。相比于push_back函数来说,下面的例子足以证实,emplace_back的入栈方式,会使其节省一次移动构造函数的调用。(小细节,C++17之后,增加了引用返回值)
#include <vector>
#include <string>
#include <iostream>
struct President
{
std::string name;
std::string country;
int year;
President(std::string p_name, std::string p_country, int p_year)
: name(std::move(p_name)), country(std::move(p_country)), year(p_year)
{
std::cout << "I am being constructed.\n";
}
President(President&& other)
: name(std::move(other.name)), country(std::move(other.country)), year(other.year)
{
std::cout << "I am being moved.\n";
}
President& operator=(const President& other) = default;
};
int main()
{
std::vector<President> elections;
std::cout << "emplace_back:\n";
elections.emplace_back("Nelson Mandela", "South Africa", 1994);
std::vector<President> reElections;
std::cout << "\npush_back:\n";
reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936));
}
// output
emplace_back:
I am being constructed.
push_back:
I am being constructed.
I am being moved.
- noexcept
使用noexcept表明函数或操作不会发生异常,会给编译器更大的优化空间。
以下情形鼓励使用noexcept:
移动构造函数(move constructor)
移动分配函数(move assignment)
析构函数(destructor)。这里提一句,在新版本的编译器中,析构函数是默认加上关键字noexcept的。下面代码可以检测编译器是否给析构函数加上关键字noexcept。
struct X
{
~X() { };
};
int main()
{
X x;
// This will not fire even in GCC 4.7.2 if the destructor is
// explicitly marked as noexcept(true)
static_assert(noexcept(x.~X()), “Ouch!”);
}
叶子函数(Leaf Function)。叶子函数是指在函数内部不分配栈空间,也不调用其它函数,也不存储非易失性寄存器,也不处理异常。
最后强调一句,在不是以上情况或者没把握的情况下,不要轻易使用noexception。
- std::chrono::duration
从C++11就有,14有强大的补充。下面列举我喜欢用的。
#include <chrono>
#include <iostream>
int main()
{
using namespace std::chrono_literals;
auto halfmin = 30s;
std::cout << "half a minute is " << halfmin.count() << " seconds\n"
<< "a minute and a second is " << (1min + 1s).count() << " seconds\n";
}