CPP Memory Flashcards

1
Q

Rule of Three

A

If a class requires one of the following, it is likely it needs all 3:

  • user-defined destructor
  • user-defiend copy-constructor
  • user-defined copy assignement operator
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Rule of Five

A

If a class follows the rules of three, move operations are defined as deleted

  • if move semantics are desired for a class, it must have all fve special member functions
  • if only move semantics are desired, all five special members must be defined, but defining the copy operations as deleted.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Copy Costructor

A

Simple, copies data, doesn’t steal, doesn’t change the object from which is copying from (that why it is const).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Move Costructor

A

Copysemantics has high costs of overhead, or is not wanted.

Move semantics provides a solution.

Move constructor is invoked: A(A&& other);

  • T a(std::move(b));
  • T a = std::move(b);
  • f(std::move(a)) with void f(T v);
  • return a; inside T f();

Move assignement: A& operator=(A&& other)

  • similar to constructor, but called when the object has been already constructed.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Smart pointers

A

include <memory></memory>

  • unique_ptr
    • Essentially RAII semantics for arbitrary pointers
    • assumes unique ownership of another C++ object through a pointer
    • automatic free when out of scope
    • almost a raw pointer -> only difference is it can only be moved, not copied.
    • members:
      • get -> returns const raw pointer
      • release -> returns raw pointer and releases ownership
    • Examples:
      • std::unique_ptr<int> valuePtr(new int(15));</int>
      • image
  • shared_ptr
    • expensive, its use should be avoided when possible
How well did you know this?
1
Not at all
2
3
4
5
Perfectly