C++11新特性
1. 自动类型推导 (auto 和 decltype)
auto
允许编译器自动推断变量的类型。decltype
提供了一种方式来获取表达式的类型。
int main ( ) {
auto i = 42 ;
decltype ( i) j = 0 ;
return 0 ;
}
2.初始化列表 (Uniform Initialization)
可以使用花括号 {}
来初始化任何类型的对象,统一了初始化语法。
int main ( ) {
int a{ 5 } ;
std:: vector< int > v{ 1 , 2 , 3 , 4 , 5 } ;
MyType obj{ } ;
MyType obj2{ 1 , 2 , 3 } ;
return 0 ;
}
3. Lambda 表达式
# include <algorithm>
# include <vector>
int main ( ) {
std:: vector< int > numbers{ 1 , 2 , 3 , 4 , 5 } ;
std:: for_each ( numbers. begin ( ) , numbers. end ( ) , [ ] ( int & n) { n *= 2 ; } ) ;
return 0 ;
}
4. 右值引用 (Rvalue References) 和移动语义 (Move Semantics)
改进了资源管理,允许更高效的资源转移而非复制。 允许函数接受和返回临时对象的引用,并通过移动语义优化资源转移,减少不必要的拷贝。
class MyClass {
public :
MyClass ( ) { }
MyClass ( const MyClass& ) { }
MyClass ( MyClass&& other) noexcept { }
} ;
MyClass createInstance ( ) {
MyClass temp;
return std:: move ( temp) ;
}
int main ( ) {
MyClass instance = createInstance ( ) ;
return 0 ;
}
5. 智能指针 (std::unique_ptr
, std::shared_ptr
, std::weak_ptr
)
提供了更好的内存管理机制,减少内存泄漏的风险。 C++11引入了std::shared_ptr
、std::unique_ptr
和std::weak_ptr
三种智能指针,用于自动管理动态分配的内存,避免内存泄漏和悬空指针。
# include <memory>
int main ( ) {
std:: unique_ptr< int > uptr ( new int ( 42 ) ) ;
std:: shared_ptr< int > sptr ( new int ( 100 ) ) ;
std:: weak_ptr< int > wptr = sptr;
return 0 ;
}
6. nullptr
nullptr
是一个新的空指针常量,用于替代NULL
或0
,提高了代码的可读性和类型安全性。
int main ( ) {
int * ptr = nullptr ;
if ( ! ptr) {
}
return 0 ;
}
7. constexpr
允许在编译时计算表达式,用于定义常量表达式或执行编译时的计算。
constexpr int factorial ( int n) {
return n <= 1 ? 1 : ( n * factorial ( n - 1 ) ) ;
}
int main ( ) {
constexpr int fact_of_5 = factorial ( 5 ) ;
static_assert ( fact_of_5 == 120 , "Factorial of 5 should be 120" ) ;
return 0 ;
}
8. 委托构造函数 (Delegating Constructors)
class C {
public :
C ( ) : C ( 0 ) { }
C ( int x) : data ( x) { }
private :
int data;
} ;
int main ( ) {
C c;
return 0 ;
}
9. 范围 for 循环 (Range-based for loop)
# include <vector>
# include <iostream>
int main ( ) {
std:: vector< int > vec{ 1 , 2 , 3 , 4 , 5 } ;
for ( const auto & elem : vec) {
std:: cout << elem << ' ' ;
}
return 0 ;
}
10. 新的标准库功能
包括新的算法、容器和其他工具,如 std::array
、std::forward_list
、std::unordered_map
/set
等。
11. 线程支持 (Concurrency Support)
提供了线程库,包括 std::thread
、std::mutex
、std::future
等,使得多线程编程更为方便。
# include <thread>
# include <iostream>
void threadFunc ( ) {
std:: cout << "Hello from another thread\n" ;
}
int main ( ) {
std:: thread t ( threadFunc) ;
t. join ( ) ;
return 0 ;
}
12. 强类型枚举
enum class Color { Red, Green, Blue } ;
Color color = Color:: Red;
13. 模板增强
template < typename T >
void print ( T arg) {
std:: cout << arg << std:: endl;
}
template < typename T , typename . . . Args>
void print ( T firstArg, Args. . . args) {
std:: cout << firstArg << ", " ;
print ( args. . . ) ;
}
14. 类型别名和类型推断
template < typename T >
using Vec = std:: vector< T> ;
Vec< int > vec = { 1 , 2 , 3 , 4 , 5 } ;
15. 属性规范
[ [ noreturn] ] void fail ( ) {
throw std:: runtime_error ( "Failed!" ) ;
}