C++新特性(C++11, C++14, C++17, C++20)

作为使用的记录,方便后续的查询,欢迎大家一起来完善。我会定期根据使用频率调整顺序。
大部分说明,都会出自cppreference网站

  1. 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.
  1. 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。

  1. 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";
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值