C++11新特新

C++11/14/17 新特性总结

  • initializer_list
1
std::vector<int> vctTemp( {1, 92, 211, 23, -1, -239, 286, 50});
  • auto
  • decltype

用于模板函数的参数返回类型声明

1
2
3
4
5
6
template <typename T, typename U>
auto MyFunc(T t, U u) -> decltype(t + u)
{
return t + u;
}

用于对lambda函数类型自动推导

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
auto func = [](int a, double b, const std::string& strTmp)->std::string {
boost::format fmt("%1% %2% %3%");
fmt % a% b% strTmp;
return fmt.str();
};

/*
auto func2 = [](int a, double b, const std::string& strTmp)->std::string {
char buf[1024] = { 0 };
memset(buf, 0, sizeof(buf));
sprintf_s(buf, "%d %.8f %s", a, b, strTmp.c_str());
return std::string(buf);
};
*/

std::map<int, decltype(func)> fucMap;

fucMap.insert( std::make_pair(0, func) );
//fucMap.insert( std::make_pair(1, );

auto it = fucMap.find(0);
BOOST_CHECK_EQUAL( fucMap.end()== it, false);
std::cout << it->second(10, 1.23, std::string("hello")) << std::endl;

  • override 和 final

override 用于来声明重写父类虚函数
final 用来修饰一个类是,表明一个类禁止被继承; 用来修饰虚函数时, 表明虚函数不能被重写

  • 函数返回类型后置 (用于模板函数)

  • 模板别名: using

1
2
3
4

typedef std::vector<std::map<std::string, std::string>>::iterator itMaps;
using itMaps = std::vector<std::map<std::string, std::string>>::iterator ;

using可以用于模板的别名定义, typedef 则不可以

1
2
3
template<typename T>
using it12Items = std::array<T, 12>;

  • nullptr
    用来取代 NULL
    1
    2
    3
    4
    5

    0 == nullptr; //true
    NULL == nullptr; //true


  • 智能指针
1
2
3
shared_ptr
unique_ptr
weak_ptr
  • 异常规范
1
2
3
4
5
6

foo()noexcept
foo()noexcept(false)
foo()noexcept(true)


  • explicit

C++11之前仅限制单个参数的构造函数做隐式转换
C+++11开始不限于单个参数的构造函数

  • 可变参数模板
    一般用递归的方式逐步减少参数的个数 , 递归终止于0个参数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

//递归结束
void XPrint()
{
}


template< typename T, typename ...Types>
void XPrint(const T& first, const Types&... otherArgs)
{
PlainPrint(first);
XPrint( otherArgs... );
}



BOOST_AUTO_TEST_CASE(test_variadic_templates)
{
std::cout << "hello ............" << std::endl;

XPrint(2, 5.231, std::string("hello"), "niuniu", std::complex(5, 1));

}

  • 右值引用和移动语义

注意自己实现移动拷贝(move ctor)的时候(有指针), 收尾时需要将被move的对象的指针设置为NULL

1
2
3
4

std::vector<std::string> vctInts;
vctInts.push_back(std::move( std::string("hello") ));

  • Copyrights © 2021-2024 youngqqcn

请我喝杯咖啡吧~