T.TAO
Back to Blog
/2 min read/Others

C++11 New Features

C++11 New Features

This article covers some new features in C++11.

Automatic Type Deduction β€” auto Keyword

The auto keyword allows the compiler to automatically deduce the type of a variable based on its initializer expression, making code more concise and reducing redundant type declarations.

For example,

Plain Textauto x = 10; // x is an int

Range-based for Loop

C++11 introduced a more concise for loop syntax for iterating over container elements. For example,

Plain Textstd::vector<int> vec = {1,2,3,4,5};
for (auto& elem: vec) {
	std::cout << elem << std::endl;
}

Smart Pointers

C++11 introduced std::unique_ptr and std::shared_ptr to automatically manage dynamic memory, avoiding errors that can arise from manual memory deallocation.

  • std::unique_ptr: Exclusive ownership, ensuring a pointer can only point to one resource.
  • std::shared_ptr: Shared ownership, where multiple pointers can share the same resource. Uses reference counting to manage resource lifecycle.

Anonymous Functions

C++11 allows Lambda expressions to concisely define anonymous functions. They are particularly suitable for callbacks and simple computations.

Plain Textauto add = [](int a, int b) -> int {
	return a + b;
};

std::cout << add(3,4) << std::endl;

Move Semantics and Rvalue References

C++11 introduced move semantics and rvalue references, denoted by the && symbol. Move semantics allow programs to avoid unnecessary copies to improve performance.

Rvalue references can bind to temporary objects (rvalues) and transfer resources through move constructors or move assignment operators.

Plain Textstd::vector<int> vec1 = {1,2,3};
std::vector<int> vec2 = std::move(vec1); 
// vec1's resources are transferred to vec2, avoiding copy

nullptr Keyword

C++11 introduced nullptr as the constant value for null pointers, replacing NULL and providing stronger type safety.

using Keyword and Type Aliases

The using keyword in C++11 can be used to create type aliases, replacing the traditional typedef syntax and being more concise in template scenarios.

Plain Textusing int_ptr = int*;

constexpr Keyword

The constexpr keyword is used to define compile-time constants. Unlike const, constexpr guarantees that the expression is evaluated at compile time.

Plain Textconstexpr int square(int x) {
	return x * x;
}

constexpr int result = square(5); 
// result is computed at compile time

Variadic Template Parameters

Explicit Default and Deleted Functions