github twitter email rss
C++
0001 Jun 1
7 minutes read

C++

Standards

-std==c++11

Reference vs pointer

reference &
pointer *

References

int var=42;
int& ref=var;   // Create a reference to var
ref=99;         // Original updated because of assignment to reference
assert(var==99);

lvalue

lvalue references can only be bound to lvalues, not rvalues

int& i = 42; // won't compile

exception is

int const& i = 42; // will compile

rvalue

rvalue references bind only to rvalues

int&& i=42;
int j=42;
int&& k=j; // Won’t compile

deleted functions

defaulted functions

constexpr

Type inference

auto

auto a = 5.0, b = 10.0
auto i = 1.0, *ptr = &a, &ref = b;
auto j = 10, str = "error"; //compile error

map<string, int> index;
auto& ref = index;
auto* ptr = &index;
const auto j = index;
const auto& cref = index;

const vector<int> values;
auto a = values;    // type of a is vetor<int>
auto& b  = values;  // type of b is const vector<int>&

volatile long clock = 0;
auto c = clock;     //  c is not volatile

JetPlane fleet[10];
auto e = fleet;     //  type of e is JetPlane*
auto& f = fleet;    // type if f is JetPlane(&)[10] - a reference

int func(dobule) { return 10; }
auto g = func;      // type of g is int(*)(double)
auto& h = func;     // type of h is int(&)(double)

int i  = 10;
auto a = 1;     // preferable
auto b(i);      // when explicit constructor

decltype

int i = 10;
cout << typeid(decltype(i + 1.0)).name() << endl; // double

vector<int> a;
decltype(a) b;
b.push_back(10);
decltype(a)::iterator iter = a.end();

template<typename X, typename Y>
auto multiply(X x, Y y) -> decltype(x * y) // return type determined by arguments types
{
    return x * y;
}

int, double, complex, Date, …
vector, string, thread, Matrix, …

auto

auto i = 42;        // i is an int
auto l = 42LL;      // l is an long long
auto p = new foo(); // p is a foo*

std::map<std::string, std::vector<int>> map;
for(auto it = begin(map); it != end(map); ++it) 
{
}

s

template <typename T1, typename T2>
auto compose(T1 t1, T2 t2) -> decltype(t1 + t2)
{
   return t1+t2;
}
auto v = compose(2, 3.14); // v's type is double

nullptr std::nullptr_t

void foo(int* p) {}

void bar(std::shared_ptr<int> p) {}

int* p1 = NULL;
int* p2 = nullptr;   
if(p1 == p2)
{
}

foo(nullptr);
bar(nullptr);

bool f = nullptr;
int i = nullptr; // error: A native nullptr can only be converted to bool or, using reinterpret_cast, to an integral type

Range-based for loops

std::map<std::string, std::vector<int>> map;
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
map["one"] = v;

for(const auto& kvp : map) 
{
  std::cout << kvp.first << std::endl;

  for(auto v : kvp.second)
  {
     std::cout << v << std::endl;
  }
}

int arr[] = {1,2,3,4,5};
for(int& e : arr) 
{
  e = e*e;
}

Override and final

class B 
{
public:
   virtual void f(int) {std::cout << "B::f" << std::endl;}
};

class D : public B
{
public:
   virtual void f(int) override final {std::cout << "D::f" << std::endl;}
};

class F : public D
{
public:
   virtual void f(int) override {std::cout << "F::f" << std::endl;}
};

Strongly-typed enums

enum class Options {None, One, All};
Options o = Options::All;

Pointers

Smart pointers

http://stackoverflow.com/questions/15648844/using-smart-pointers-for-class-members

unique_ptr:

should be used when ownership of a memory resource does not have to be shared (it doesn’t have a copy constructor), but it can be transferred to another unique_ptr (move constructor exists).

	void foo(int* p)
	{
	   std::cout << *p << std::endl;
	}
	std::unique_ptr<int> p1(new int(42));
	std::unique_ptr<int> p2 = std::move(p1); // transfer ownership

	if(p1)
	  foo(p1.get());

	(*p2)++;

	if(p2)
	  foo(p2.get());

shared_ptr:

should be used when ownership of a memory resource should be shared (hence the name).
``` void foo(int* p)

{
}
void bar(std::shared_ptr<int> p)
{
   ++(*p);
}
std::shared_ptr<int> p1(new int(42));
std::shared_ptr<int> p2 = p1;

bar(p1);   
foo(p2.get());

auto p3 = std::make_shared<int>(42);

### weak_ptr: 
holds a reference to an object managed by a shared_ptr, but does not contribute to the reference count; it is used to break dependency cycles (think of a tree where the parent holds an owning reference (shared_ptr) to its children, but the children also must hold a reference to the parent; if this second reference was also an owning one, a cycle would be created and no object would ever be released).
```	auto p = std::make_shared<int>(42);
	std::weak_ptr<int> wp = p;

	{
	  auto sp = wp.lock();
	  std::cout << *sp << std::endl;
	}

	p.reset();

	if(wp.expired())
	  std::cout << "expired" << std::endl;

Lambdas

http://msdn.microsoft.com/en-us/library/dd293603.aspx
function object, functor, std::function

std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);

std::for_each(std::begin(v), std::end(v), [](int n) {std::cout << n << std::endl;});

auto is_odd = [](int n) {return n%2==1;};
auto pos = std::find_if(std::begin(v), std::end(v), is_odd);
if(pos != std::end(v))
  std::cout << *pos << std::endl;

std::function<int(int)> lfib = [&lfib](int n) {return n < 2 ? 1 : lfib(n-1) + lfib(n-2);};

non-member begin() and end()

C-like array

int arr[] = {1,2,3};
std::for_each(&arr[0], &arr[0]+sizeof(arr)/sizeof(arr[0]), [](int n) {std::cout << n << std::endl;});

auto is_odd = [](int n) {return n%2==1;};
auto begin = &arr[0];
auto end = &arr[0]+sizeof(arr)/sizeof(arr[0]);
auto pos = std::find_if(begin, end, is_odd);
if(pos != end)
  std::cout << *pos << std::endl;

C-like array begin() and end()

int arr[] = {1,2,3};
std::for_each(std::begin(arr), std::end(arr), [](int n) {std::cout << n << std::endl;});

auto is_odd = [](int n) {return n%2==1;};
auto pos = std::find_if(std::begin(arr), std::end(arr), is_odd);
if(pos != std::end(arr))
  std::cout << *pos << std::endl;

std::vector begin() and end()

template <typename Iterator>
void bar(Iterator begin, Iterator end) 
{
   std::for_each(begin, end, [](int n) {std::cout << n << std::endl;});

   auto is_odd = [](int n) {return n%2==1;};
   auto pos = std::find_if(begin, end, is_odd);
   if(pos != end)
      std::cout << *pos << std::endl;
}

template <typename C>
void foo(C c)
{
   bar(std::begin(c), std::end(c));
}

template <typename T, size_t N>
void foo(T(&arr)[N])
{
   bar(std::begin(arr), std::end(arr));
}

int arr[] = {1,2,3};
foo(arr);

std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
foo(v);

static_assert and type traits

template <typename T, size_t Size>
class Vector
{
   static_assert(Size < 3, "Size is too small");
   T _points[Size];
};

int main()
{
   Vector<int, 16> a1;
   Vector<double, 2> a2;
   return 0;
}


template <typename T1, typename T2>
auto add(T1 t1, T2 t2) -> decltype(t1 + t2)
{
   static_assert(std::is_integral<T1>::value, "Type T1 must be integral");
   static_assert(std::is_integral<T2>::value, "Type T2 must be integral");

   return t1 + t2;
}

Move semantics

http://www.codeproject.com/Articles/570638/Ten-Cplusplus11-Features-Every-Cplusplus-Developer

callable type

class background_task
{
public:
    void operator()() const
    {
    do_something();
    do_something_else();
    }
};
background_task f;
std::thread my_thread(f);

BOOST

time

http://en.cppreference.com/w/cpp/chrono/c/strftime

http://www.boost.org/doc/libs/1_52_0/more/getting_started/unix-variants.html
http://www.boost.org/doc/libs/1_41_0/doc/html/date_time/examples.html#date_time.examples.days_alive
http://stackoverflow.com/questions/3404393/date-time-parsing-in-c-any-format-string-to-epoch
http://stackoverflow.com/questions/11204265/converting-date-and-time-string-to-unsigned-int64-in-c?lq=1
http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost

How many ways are there to initialize a primitive data type in C++ and what are they?
Why should you declare a destructor as virtual?
What does it mean that C++ supports overloading?
What are examples of overloading in C++?
What is name mangling in C++ and why is it used?
What is an abstract base class?
What is RTTI?
How can you access a variable that is “hidden” by another variable of the same name?
What is a namespace and how is it used.
What are the differences between a class and a struct in C++, and how does this compare to C?
What are templates? How are they used?
What is a copy constructor and when is it used, especially in comparison to the equal operator.
What is the difference between a “shallow” and a “deep” copy?
What is the const operator and how is it used?
What are the differences between passing by reference, passing by value, and passing by pointer in C++?
When is it and when is it not a good idea to return a value by reference in C++?
What is the difference between a variable created on the stack and one created on the heap?
How do you free memory allocated dynamically for an array? What are the implications of just using delete?
What is multiple inheritance? When should it be used?
What is a pure virtual function?
What does the keyword mutable do?
What does the keyword volatile do?
What is the STL?
What is a Vector?
What is contained in the header?
What is the difference between #include and #include ?
What’s the difference between “++i” and “i++”?
What is short circuit evaluation? How can it be used? Why can is be dangerous?
What is the ‘,’ operator?
What is the only ternary operator? How is it used?
What is the use of a const member function and how can it be used?
How is try/catch used in C++?
Why should you never throw an exception in a destructor?
What is the explicit keyword?
What is the proper way to perform a cast in C++?
What does inline do?

http://www.cplusplus.com/reference/stl/
Lambda Expressions in C++ http://msdn.microsoft.com/en-us/library/dd293608.aspx
http://en.wikipedia.org/wiki/Smart_pointer
https://en.wikipedia.org/wiki/Run-time_type_information
https://en.wikipedia.org/wiki/Name_mangling
http://lemniscape.blogspot.ru/2009/02/memory-stomp-strategies.html


Back to posts


comments powered by Disqus