DEV Community

JaeHyun Park
JaeHyun Park

Posted on

Key Features of C++11

Key Features

- Automatic Type Deduction (auto)

  • Description : Allows the compiler to automatically deduce the type of a variable.
  • Example Code
auto x = 10; // x is deduced to be an int
auto y = 3.14; // y is deduced to be a double
Enter fullscreen mode Exit fullscreen mode
  • Benefit: Improves code readability and is especially convenient when dealing with complex types.

- Range-Based For Loop (range-based for loop)

  • Description: A new for loop that allows easy iteration over all elements in a container.
  • Example Code
std::vector<int> vec = {1, 2, 3, 4};
for (int n : vec) {
    std::cout << n << " ";
}

Enter fullscreen mode Exit fullscreen mode
  • Benefit: Makes the code more concise by eliminating the need to manually handle iterators.

- Lambda Expressions (lambda expressions)

  • Description: A feature that allows the creation of anonymous function objects in a concise manner.
  • Example Code:
auto add = [](int a, int b) { return a + b; };
std::cout << add(2, 3) << std::endl; // Outputs 5
Enter fullscreen mode Exit fullscreen mode
  • Benefit: Increases flexibility by allowing the easy definition of callback functions or one-time-use function objects.

- Smart Pointers (smart pointers)

  • Description: Smart pointers like std::unique_ptr and std::shared_ptr automate memory management.
  • Example Code
std::unique_ptr<int> p = std::make_unique<int>(10);
Enter fullscreen mode Exit fullscreen mode
  • Benefit: Prevents memory leaks and allows clear management of resource lifecycles.

- Move Semantics and Rvalue References

  • Description: A feature that enables the transfer (move) of object ownership, particularly useful for reducing the cost of copying large objects.
  • Example Code
std::vector<int> v1 = {1, 2, 3};
std::vector<int> v2 = std::move(v1); // v1's resources are moved to v2
Enter fullscreen mode Exit fullscreen mode

- constexpr and Constant Expressions

  • Description: A feature that defines constant expressions that can be evaluated at compile-time.
  • Example Code
constexpr int square(int x) { return x * x; }
Enter fullscreen mode Exit fullscreen mode
  • Benefit: Enhances runtime performance by ensuring that computations are completed during compile time.

- Thread Support

  • Description: Introduces support for multithreading programming in the standard library (e.g., std::thread, std::mutex).
  • Example Code
std::thread t([] { std::cout << "Hello from thread!" << std::endl; });
t.join();
Enter fullscreen mode Exit fullscreen mode
  • Benefit: Simplifies the implementation of multithreaded programs by providing standardized thread management.

Top comments (0)