Programmer's Blog

Programmer's reference

Monthly Archives: April 2016

[C++] Check memory leaks by top

top -b -n 1

To see applications which are leaking memory, look at the following columns:

RPRVT – resident private address space size
RSHRD – resident shared address space size
RSIZE – resident memory size
VPRVT – private address space size
VSIZE – total memory size


[RHEL] update dev packages

yum update

yum install libtool gcc-c++ glib*

# This installs autoconf, automake, cloog-ppl, cpp, gcc, mpfr, ppl

yum groupinstall "development tools"

[C++] 49 C++ tips

1. Initialization list of constructor: demo(int& val) : m_val(val),m_val2(val2) 
 why? Initialize const variables before the constructor.

2. call base class constructors by demo() : public demobase

3. std::copy (bar.begin(),bar.end(),back_inserter(foo)); //front_inserter

4. mymap.insert ( std::pair<char,int>('a',100) );

std::map<char,int>::iterator it = mymap.begin();
 mymap.insert (it, std::pair<char,int>('b',300)); // max efficiency inserting
 mymap.insert (it, std::pair<char,int>('c',400)); // no max efficiency inserting

6. anothermap.insert(mymap.begin(),mymap.find('c')); //range insert:from begin 
until before c

7. Disable copy constructor and operator =
thread_guard(thread_guard const&)=delete;
thread_guard& operator=(thread_guard const&)=delete;

8. Thread may be launched with argument passed by reference, in this case it 
should use std::ref(data) when setting up the thead instead of &.
std::thread t(update_data_for_widget,w,std::ref(data));

9. X my_x;
std::thread t(&X::do_lengthy_work,&my_x);

10. unique_ptr<T> myPtr(new T); 
unique_ptr<T> myOtherPtr = std::move(myPtr);

std::thread t(process_big_object,std::move(p));

11. move a thread into a function f(std::move(t));

12.dont pass reference and pointer to protected data outside the scope of lock, 
because malicious code can get the access of protected data.

13. const Function --> cannot change member variable except defined "mutable", 
speed up the compilation.

14. ctor never throws, copy constructor pass by value and make a copy

15. conversion constructor Boo(int i); --> Boo BooObject = 10;
 conversion operator operator double() { return value } --> double i = BooObject;

16. Signal constructor fail, throw an exception.
 handle destructor fail, only log, cannot throw since it will coredump, dtor 
cannot overload

17. virtual destructor --> delete without type;

18. order of destruction of array is from last element

19. Before ctor is run, its member and base class member are created.

20. force dtor before close of program --> use scope { }

21. Named ctor idiom: 
static Point rectangular(float a, float b); 
static Point polar (float a, float b);
inline Point::Point(float x, float y) : x_(x), y_(y) {}
inline Point Point::rectangular(float x , float y);
inline Point Point::polar(float radius, float angle);
--> Point p1 = Point::retangular(3,5);

22. Disadvantage of multiple inheritance --> messy function name and 

23. explicit function not allow implicit converstions

24. Create deadlock without lock: join on each other thread.

25. Avoid deadlock: 
  1. Avoid nested lock(lock() for multiple)
  2. Avoid calling user code in locking
  3. acquire lock in order

26.std::lock_guard<std::mutex> lock_b(rhs.m,std::adopt_lock);
call_once(once_flag& flag, [](){}); //only call once by a thread

27. thread_local object is local variable of each thread when created

28. extern variable must be defined outside and without "static" 

29. auto f6=std::async(std::launch::async,Y(),1.2);
auto f7=std::async(std::launch::deferred,baz,std::ref(x));
auto f8=std::async(
std::launch::deferred | std::launch::async,
auto f9=std::async(baz,std::ref(x));

//auto is future<int>

30. If future throws an exception, the .get() will throw exception

31. packaged_task
int countdown (int from, int to);

std::packaged_task<int(int,int)> tsk (countdown);
std::future<int> ret = tsk.get_future(); 
//for non-threaded program, invoke the pakaged_task by running itself, tsk();

std::thread th (std::move(tsk),10,0); 
 int value = ret.get(); 


32. Promise //set_exception//get_future//set_value//swap
std::promise<int> prom; // create promise
std::future<int> fut = prom.get_future(); // engagement with future

std::thread th1 (print_int, std::ref(fut)); // send future to new thread

prom.set_value (10); // fulfill promise

33. Promise can be used to handle queue/connection
 data_packet data=connection->incoming();
 std::promise<payload_type>& p=

 outgoing_packet data=

34. chrono
Objects of class system_clock represent wall clock time from the system-wide 
realtime clock.
Objects of class steady_clock represent clocks for which values of time_point 
never decrease as physical time advances and for which values of time_point 
advance at a steady rate relative to real time. That is, the clock may not be 
Objects of class high_resolution_clock represent clocks with the shortest 
tick period. high_resolution_clock may be a synonym for system_clock or 

cv.wait_until(lock, time_point, predicate); predicate [] { i= 1 }; 
//if predicate is not true, put the thread into sleep again

35. vector::emplace_back -> insert element while initialize

36. atomic object cant be copied or assigned since, operation on two different 
object is non-atomic

37. must unique lock for CV.wait(lk);
future f = prom.get_future();
shared_future sf = f.share();

38. bind(a, 6);
thread t4([](int x){return x*x;}, 6);
thread t6(&A::f, move(a), 8 'w'); //a.f(8, 'w');

39. memory order sync, the order must be sequential within same thread
Thread 1:, memory_order_relaxed);, memory_order_release);

Thread 2:
if (x.load(memory_order_relaxed));

New method:
atomic<int> sync;
t1., memory_order_release);
t2. while(!sync.compare_exchange_strong(1,2,memory_order_acq_rel));
t3. while(sync.load(memory_order_acquire);

40. while(!head.compare_exchange_weak(new_node->next, new_node);
if the comparison is false, that means another thread is using the function, so
this line will follow the other thread setting head point to new_node->next,
once the other thread use over, it will return true head will point to new_node.

41. use compare_exchange_strong() if something is in while loop and may cause spurious failure 
of compare_change_weak().

42. Once Associative containers (set, maps) key is set, if we change the key (with const_cast), 
the container don’t know to insert to right pos.

43. Recursive mutex: lock more than once to prevent a deadlock -> in recursive function, 
no extra entry point function

44. Change to lock_guard (scoped lock) using adopt_lock after locking

45. New in cpp 11: lambda expressions, auto type, container initializer,
default functions, nullptr, delegating constructors (M() : M(0)), rvalue references (M(M&&))

46. Packaged task -> allocating the task into the thread

47. Async launch::deferred, run the thread when calling future_get

48. volatile: compiler optimization expect unchanged, but other threads/programs might change.

49. Shared_future: can get multiple times -> for copy constructable objects (originally moveConstructable)