Skip to content

Instantly share code, notes, and snippets.

View meshell's full-sized avatar

Michel Estermann meshell

View GitHub Profile
@meshell
meshell / CppUG_RAII_main.cpp
Last active February 22, 2016 20:21
RAII example using unique_ptr
#include <cstdio>
#include <cstdlib>
#include <memory>
int main()
{
auto file_open = [](const char* filename, const char* mode) -> FILE*
{
return std::fopen(filename, mode);
};
@meshell
meshell / CppUG_SmartPointers.cpp
Created February 22, 2016 20:20
Smart_Pointers
// unique object ownership
auto unique = std::unique_ptr<widget>(new widget());
auto unique = std::make_unique<widget>();
// shared object ownership
auto shared = std::make_shared<widget>();
// weak reference to an object managed by std::shared_ptr
std::weak_ptr<widget> weak = shared;
@meshell
meshell / CppUG_double_linked_list.h
Created February 22, 2016 20:31
Addaption of the Double Linked list from http://www.cprogramming.com/snippets/source-code/double-linked-list-cplusplus using C++11 smart pointers.
#ifndef DOUBLE_LINKED_LIST_H
#define DOUBLE_LINKED_LIST_H
#include <vector>
#include <memory>
#include <iostream>
template<typename T>
struct Node {
explicit Node(T val)
@meshell
meshell / CppUG_pimpl.cpp
Created February 22, 2016 20:40
Stupid PIMPL example.
#include "pimpl.h"
#include <iostream>
#include <string>
#include <vector>
class foo::impl {
public:
void initialize() {
member1 = "Hello";
@meshell
meshell / CppUG_Rule_of_Five.h
Last active February 22, 2016 20:54
Rule of Five
#include <cstring>
#include <iostream>
class foo
{
public:
// Constructor
explicit foo(const char* arg) : cstring{new char[std::strlen(arg)+1]}
{
std::strcpy(cstring, arg);
@meshell
meshell / CppUG_CopySwap.h
Created February 22, 2016 21:00
Copy and Swap idiom
#include <cstring>
#include <iostream>
class foo
{
public:
explicit foo(const char* arg) : cstring{new char[std::strlen(arg)+1]} {
std::strcpy(cstring, arg);
}
~foo() {
@meshell
meshell / CppUG_Rule_of_Zero.h
Last active February 22, 2016 21:05
Rule of Zero
#include <string>
class foo {
public:
// Constructor
foo(const std::string& arg) : cppstring(arg) {}
private:
std::string cppstring
};
class base {
public:
virtual ~base() = default;
base(const base&) = default;
base(base&&) = default;
base& operator=(const base&) = default;
base& operator=(base&&) = default;
};
@meshell
meshell / CppUG_EraseRemove.cpp
Created February 22, 2016 21:12
Erase Remove idiom
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {1, 2, 3, 4, 2, 5, 2, 6};
v.erase(std::remove(std::begin(v),
std::end(v),
2),
std::end(v));
// Until C++11
template<class T>
struct p
{
typedef T* Type;
};
p<float>::Type y; // y is of type float*
// Since C++11: alias template
template<class T>