Sign in with Google to keep private notes

C++ initialisation

objects are not instantiations of classes. It's just a region of storage.

objects can live in CPU registers, they don't necessarily live in RAM

int a, b;          // valid
int a, double b;   // invalid

different kinds of initalisation in C++

int a;       // default-initialization
int b = 5;   // copy-initialization
int c(5);    // direct-initialization. Different from {} 
//for e.g. with a vector this initialises size 5
//due to most vexing parse, we do prefer to use {} instead of (). It looks like a func...


//curly brace stuff:
int d{5};    // direct-list-initialization. Prevents narrowing initialisations
int e{};     // value-initialization. Use this to prevent UB due to leftover garbage

[[maybe_unused]] will suppress Werror warnings from the compiler, but no promises the variable itself is compiler folded.

The most vexing parse says that anything that can be interpreted as a function declaration will be interpreted like that. Often, when you meant to declare a local variable, the compiler takes it as a function declaration and therefore it will fail on later lines.

Designated Initialisers:

struct Time { int hour; int minute; };
struct Date { Time t; int year; int month; int day; };

Date d { 
    .t { .hour = 10, .minute = 35 }, 
    .year = 2050, .month = 5, .day = 10 
};

Make sure arguments come in the order specified. Make sure not to nest them.

Some names are reserved even though they aren't keywords

int __count; // reserved for implementations
int _Count;  // reserved, also, these are for global namespace
int _count;  // avoid

override and final aren't reserved keywords

C++ has special identifiers that acquire meaning only in certain contexts.

int override = 5; // valid
int final = 10;   // valid

Yet:

struct Base {
    virtual void foo();
};

struct Derived : Base {
    void foo() override;
};

C++ uses capitalised words for user defined types, and uses camel case for everything else.

Debug builds might secretly initialize your variables

int x;

std::cout << x;

In certain Visual Studio debug configurations, uninitialized storage is filled with a recognizable pattern:

0xCCCCCCCC

Interpreted as a 32-bit signed integer, this is −858993460.

This is not initialization guaranteed by the C++ language.

Unexpected: Your program might consistently print the same garbage value in debug mode, then behave differently in release mode.

Undefined behaviour

Behavior for which this International Standard imposes no requirements

Consider:

int x; // uninitialized

if (x == 5) {
    std::cout << "Five\n";
} else {
    std::cout << "Not five\n";
}

std::cout << "Done\n";

What you'd intuitively expect

Even if x contains garbage:

  1. If x == 5, print "Five".

  2. Otherwise, print "Not five".

  3. Regardless, print "Done".

What the compiler is actually allowed to do

Because reading the uninitialized x is undefined behavior, the compiler has no obligation to preserve any of those expectations.

For example, it could theoretically optimize the entire program into:

int main()
{
    std::cout << "Five\n";
}

Notice that "Done" disappeared, even though that statement doesn't use x!

This is permitted because the original program already has undefined behavior.

Why would the compiler do that?

Compilers optimize under the assumption that your program doesn't execute undefined behavior.

They can reason:

  • For a program with defined behavior, this uninitialized read cannot occur.

  • Therefore, they don't need to preserve what happens on this execution path.

  • Optimizations can consequently remove or rearrange code that appears unrelated.

In debug mode it might correctly initialise the value but during O2 runtime its performance could be completely different.

raw memory manipulation

UB is generally not allowed, except in the case of 1 byte types.

unsigned char c;
unsigned char d = c; // Allowed in C++20

moving those bytes around is ok, but interpreting it as a number is still undefined behaviour

int x = c; //noooooooooooooooo

types of problems

  • Unspecified behavior: The implementation can choose any permitted outcome, potentially differently each time. It doesn't need to document its choice.
  • Implementation-defined behavior: The implementation must choose a permitted behavior and document its choice. That choice typically stays consistent for a given implementation/configuration.

Operators

<< is the insertion operator

>> is the extraction operator

new, delete and throw are all operators as well

Unary, binary (left and right), tertiary (conditional) and nullary (throw)

x = 5 and cout << x both have obvious side effects. But they also have return types, return types which can be used for chaining. They both return LHS. In the case of cout << x this is why you can do cout << x << ' ' << y << endl etc.. Under the hood it look like

std::ostream& operator<<(std::ostream& os, int x)
{
    // Write x to os
    return os;
}

Which kind of looks like

((std::cout << a) << b) << c;

below is still unformatted

Abstractly, a stream is just a sequence of bytes that can be accessed sequentially. Over time, a stream may produce or consume potentially unlimited amounts of data. Input streams are streams of data for us the program to consume, output streams are streams for external programs to consume.

  1. cin -- an istream object tied to the standard input (typically the keyboard)
  2. cout -- an ostream object tied to the standard output (typically the monitor)
  3. cerr -- an ostream object tied to the standard error (typically the monitor), providing unbuffered output
  4. clog -- an ostream object tied to the standard error (typically the monitor), providing buffered output
#include <iomanip>
char buf[10]{};
std::cin >> std::setw(10) >> buf; //how to stop before you overflow

<< is called the extraction operator. The extraction operator hops over whitespaces. If you would want to get all the chars, you can use the .get() method or the overloaded version that gets the string and max capcaity first

char ch {};
std::cin.get(ch); //get one char at a time and place it in the ch buffer

char strBuf[11] {};
std::cin.get(strBuf, 11); //you can get 10 chars at one time and place it in the str buf

//and if you have multiple lines use getline() with the same signature to get around some kind of \n bug 
//causing issue
//im not gonna make it, am i?

if you would like to write directly to a string, include the string header, and use an overload

#include <string>
#include <iostream>

int main()
{
    std::string strBuf{};
    std::getline(std::cin, strBuf);
    std::cout << strBuf << '\n';

    return 0;
}

ignore() discards the first character in the stream.
ignore(int nCount) discards the first nCount characters.
peek() allows you to read a character from the stream without removing it from the stream.
unget() returns the last character read back into the stream so it can be read again by the next call.
putback(char ch) allows you to put a character of your choice back into the stream to be read by the next call.

Use [[maybe_unused]] to allow initialisation

dont do int a, b =5; it should be int a = 5, b = 5;. The original format is not nearly as preferred.

using the extractor operator on std::endl leads to a flushed buffer

Why are designated initializers handy?

One of the main reasons to use this new kind of initialization is to increase readability.

It’s easier to read:

struct Date {
    int year;
    int month;
    int day;
};

Date inFuture { .year = 2050, .month = 4, .day = 10 };

Than:

Date inFuture { 2050, 4, 10 };

In the case of the date class, it might not be clear what’s the order of days/month or month/days. With designated initializers, it’s effortless to see the order.

Possible errors:

struct Date {
    int year;
    int month;
    int day;
    MinAndHour mh;

    static int mode;
};

Date d1 { .mode = 10; }             // err, mode is static!
Date d2 { .day = 1, .year = 2010 }; // err, out of order!
Date d3 { 2050, .month = 12 };      // err, mix!
Date d4 { .mh.min = 55 };           // err, nested!

std:cerr is unbuffered by default

However, it does explicitly state that std::cerr must be unbuffered by default. This is because if the program crashed, aborted, deadlocked, or otherwise failed before the buffer could be flushed, we could lose important diagnostics that would not get printed.

...i can make use of the std::stringstream buffer for...um...things...

stringstream is backed by a character buffer. Initializing it with a string initializes the buffer with that string, in this case a. Calling str() returns the contents of the buffer, and we print a. operator<< writes to the next position in the buffer, in this case the beginning of the buffer, overwriting whatever is already there. A b is written, overwriting the a which was previously in the buffer. Finally, str() is called again, this time printing b.

size stuff

Static members are really not part of the class object. They won't be included in object's layout.

Every distinct object must have a unique address so even uninitialised lambdas will take 1 byte of space (for the pointer).

Byte alignment or byte padding (choosing the former leads to 0 padding)

Subtracting with unsigned integers temporarily promotes them (with static_cast)

Size of the base class will be included too

virtual functions at all add 4 bytes to the class size. the 4 bytes is to the virtual page table

then if there are multiple classes inheriting from the same class with a virtual pointer, those multiple classes only accrue an additional 4 bytes owing to that virtual pointer

why am i learning this?

class ABase{ //4
        int iMem; 
}; 
 
class BBase : public virtual ABase { //4 + 4 + 4 = 12
        int iMem; 
}; 
 
class CBase : public virtual ABase { //4 + 4 + 4 = 12 
        int iMem; 
}; 
 
class ABCDerived : public BBase, public CBase { //not 12 + 12 + 4. The 4 which pointing to the virtual page table is for both already
        int iMem; 
};  

fixed width integers

the best way to get around the whole variable int debacle is to make use of uint_{size}_t

an oversight in the language does mean that uint_8_t and int_8_t will be treated as chars

unsigned ints will wrap around and this is the defined behaviour. int_8_t does the wrap around

so using the extractor operator on them will cause them to be treated instead as chars

floating points

a floating point can store at max 2^53 and after that due to the limited precision you lose any additional 1 you add to it

1.23 in C++ is counted as a double. if you want to make it a float you have to use 1.23f

Floating points actually represent preset values with preset ranges between them. this means if you use std::numeric_limits<double>::max() subtracting 1. from it leads to no change in value.

return type from templated question

The correct answer is "compile-time error". Function return type deduction with the auto specifier follows the template argument deduction rules. As a result, the compiler deduces the return type as int (T), instead of int& (T&), thus returning a prvalue instead of an lvalue reference. Therefore, a compile-time error is raised since you cannot assign to a prvalue. To address this, one can use decltype(auto) (since C++14) or trailing return type syntax (since C++11) to enable decltype type deduction rules for return type deduction instead, which would return int& (T&) as expected.

panic switching to normal questions

.reserve() ensures it resizes to fit the capacity.

.resize() can destroy previous elements if its smaller

[[no_unique_address]] allows a compiler time optimisation for structs and ensure they don't take up any space

Articles to read next