Friday, 22 May 2015

std::move overload resolution


#include 
class A
{
public:
  A(){}
  A(A& other) { std::cout << "copy ctor" << std::endl; }
  A(const A& other) { std::cout << "const copy ctor" << std::endl; }
  A(A&& other) { std::cout << "move ctor" << std::endl; }
};

class B
{
public:
  B(){}
  B(B& other) { std::cout << "copy ctor" << std::endl; }
  B(const B& other) { std::cout << "const copy ctor" << std::endl; }
};

class C
{
public:
  C(){}
  C(C& other) { std::cout << "copy ctor" << std::endl; }
};

int main()
{
  A a1;
  A a2(std::move(a1)); // move ctor called
  
  B b1;
  B b2(std::move(b1)); // const copy ctor called
  
  C c1;
  // C c2(std::move(c1)); // compile-time error: no matching constructor for initialization of 'C'

  return 0;
}
    C c1;
    const C &c2 = std::move(c1); // OK: const reference can bind to rvalue
    C && c3 = std::move(c1); // OK: rvalue reference
    // C &c4 = std::move(c1); // Error: Non-const reference cannot bind to rvalue
    // C c5 = std::move(c1); // Error: No move constructor or const copy constructor in C
Quote: "Rvalue references can be used to extend the lifetime of a modifiable temporary (note, lvalue references to const can extend lifetimes too, but they are not modifiable)"

Setup clang compiler in Kdevelop


1. Install clang compiler with "sudo apt-get install clang-3.5"
2. In CMakeLists.txt of the project add at the very top of the file (before any other tags, like cmake_minimum_required() or project())
set(CMAKE_C_COMPILER "/usr/bin/clang-3.5")
set(CMAKE_CXX_COMPILER "/usr/bin/clang++-3.5")
3. In Kdevelop right-click on the project->Open Configuration->click on CMake tab->Click on a green plus button to configure new build directory. Put in a name for the new folder, like /home/d/projects/SomeProject/build_clang. Click "Apply" button. The Build console should print something like:
-- The C compiler identification is Clang 3.5.0
-- The CXX compiler identification is Clang 3.5.0
-- Check for working C compiler: /usr/bin/clang-3.5
-- Check for working C compiler: /usr/bin/clang-3.5 -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/clang++-3.5
-- Check for working CXX compiler: /usr/bin/clang++-3.5 -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
...