Featured image of post C++14 in a Nutshell

C++14 in a Nutshell

C++14 in a Nutshell

C++14 in a Nutshell

A Brief History (With Minimal Yawning)

Back in 2011, C++ got a massive facelift with C++11. People were hyped. Lambdas! Smart pointers! auto everywhere!

Then reality hit. Some of the features were a little rough around the edges. Some syntaxes were… let’s just say “suboptimal.” So, in 2014, the C++ committee rolled out C++14 as a refinement. Not a complete overhaul, but a set of tweaks, improvements, and bug fixes to make the C++11 experience smoother.

What Changed? (Or: Why Should You Care?)

1. Return Type Deduction for Functions

Remember auto in C++11? Well, now you can use it in function return types without explicitly specifying decltype.

1
2
3
4
5
6
7
8
9
#include <iostream>

auto add(int a, int b) {
    return a + b;
}

int main() {
    std::cout << add(5, 10) << std::endl;
}

No more decltype madness!

2. Generic Lambdas

Lambdas got a lot cooler. You no longer have to specify parameter types manually.

1
2
3
4
5
6
7
#include <iostream>

int main() {
    auto print = [](auto x) { std::cout << x << std::endl; };
    print(42);
    print("Hello, C++14!");
}

It’s like templates, but lazier.

3. std::make_unique

C++11 gave us std::unique_ptr, but making one required this clunky syntax:

1
std::unique_ptr<int> ptr(new int(42));

Now, C++14 makes it easier:

1
2
3
#include <memory>

std::unique_ptr<int> ptr = std::make_unique<int>(42);

No more new keyword. Less boilerplate. More happiness.

4. Binary Literals

Ever wanted to write binary numbers without doing mental gymnastics? Now you can!

1
int flags = 0b101010;  // 42 in binary

Much easier to read than octal. (Unless you’re a robot.)

5. std::exchange

A simple utility that swaps out a value and returns the old one. Great for stateful objects!

1
2
3
4
5
6
7
8
#include <iostream>
#include <utility>

int main() {
    int x = 10;
    int old_x = std::exchange(x, 20);
    std::cout << "Old: " << old_x << ", New: " << x << std::endl;
}

It’s like std::swap, but with benefits.

6. constexpr Improvements

constexpr got a buff. Now you can have loops and more complex logic inside constexpr functions.

1
2
3
4
5
6
constexpr int factorial(int n) {
    int result = 1;
    for (int i = 2; i <= n; ++i)
        result *= i;
    return result;
}

Compile-time factorials. Because why not?

7. Deprecating std::gets (Finally!)

std::gets was removed. It was a security nightmare. If you’re still using it, stop. Right now. Please.


Key Ideas

ConceptSummary
Return Type Deductionauto can deduce function return types
Generic LambdasLambdas now support auto parameters
std::make_uniqueCleaner syntax for std::unique_ptr
Binary Literals0b101010 is now valid C++
std::exchangeSwaps out a value and returns the old one
constexpr LoopsMore powerful constexpr logic
std::gets RemovedGood riddance!

References