[Dive into C++] Semantics, Smart Pointers


1 Semantics

Semantics 3 category:

  • value semantics / copy semantics
  • move semantics
  • reference semantics / pointer semantics

Semantics is an attribute of a data type.

1.1 Value Semantics / Copy Semantics

  • Intended to be copied
  • Must use = to modify data
  • Implies immutability of the object

1.2 Move Semantics

  • Based on rvalue references
  • The data is moved instead of copying, far more efficient

1.3 Reference Semantics / Pointer Semantics

  • Value can be large and bulky.
  • The most basic example is raw pointers.

2 Smart Pointers

  • An data type which simulates a pointer.
  • Is a class which wraps a raw pointer.
  • Provides automatic memory management and prevents the chances of memory leaks.
template<class T>
class NaiveSmartPointer
{
public:
      explicit NaiveSmartPointer(T* p = nullptr) { rawPointer = p; }
      ~NaiveSmartPointer() { delete rawPointer; }
      T& operator* () { return *rawPointer; }
private:
      T* rawPointer;
};

int main()
{
      NaiveSmartPointer<int> x = NaiveSmartPointer<int>(new int(666));
      std::cout << *x << std::endl;
}

C++11 introduces:

  • unique_ptr
  • shared_ptr
  • weak_ptr

They are all containers for a raw pointer.

2.1 unique_ptr

  • allows only one owner of the underlying pointer
  • the destructor of it will delete the object
  • when exception comes then also de-allocate the memory
  • overload is very low
  • can not copy a unique_ptr
    • copy constructor and copy assignment operators are explicitly deleted
  • std::move() can be used to transfer ownership to another unique_ptr
#include <iostream>
#include <memory>

int main()
{
      std::unique_ptr<int> x = std::make_unique<int>(4);
      std::unique_ptr<int> y = x;  // Invalid: can't copy
      std::cout << *x << std::endl;  // 4
      std::unique_ptr<int> z = std::move(x);  // Valid: now x can't be 
used
      std::cout << *z << std::endl;  // 4
}
  • get: get raw pointer
  • release: release ownership and return raw pointer
  • reset: the managed pointer will get replaced, sp1.reset(p2), previous pointer deleted
  • swap: two unique pointer swap

2.2 shared_ptr

  • allows multiple owners of the same pointer
  • maintains a reference count of ownership
  • overload is higher than unique_ptr
  • destroy data when no reference to it

2.3 weak_ptr

  • a special type of shared_ptr which doesn’t count the reference
  • created from an existing shared_ptr
  • won’t affecting shared_ptr’s reference count
  • when shared_ptrs destroyed data, weak_ptr copies become nullptr
  • can not be dereferenced

References


Leave a Reply

Your email address will not be published. Required fields are marked *

css.php