Advertisement
mbazs

C++ copy elision

Dec 25th, 2021
1,765
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. // -------------------------------------------------
  2. // CMakeLists.txt
  3. // -------------------------------------------------
  4. cmake_minimum_required(VERSION 3.5)
  5. project(cpp4 LANGUAGES CXX)
  6.  
  7. set(CXX_VER "11")
  8. set(NO_COPY_ELISION 0)
  9.  
  10. set(CMAKE_CXX_FLAGS "-std=c++${CXX_VER} -O0 -DCXX_VER=${CXX_VER}")
  11. if (NO_COPY_ELISION)
  12.     set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-elide-constructors")
  13. endif()
  14. set(CMAKE_CXX_STANDARD_REQUIRED ON)
  15. add_executable(cpp4 main.cpp)
  16.  
  17.  
  18. // -------------------------------------------------
  19. // main.cpp
  20. // -------------------------------------------------
  21. #include <iostream>
  22. #include <utility>
  23. #include <string>
  24.  
  25. #define ENABLE_COPY_CTOR
  26. //#define ENABLE_MOVE_CTOR
  27.  
  28. struct A {
  29.     A() {
  30.         std::cout << "A()" << std::endl;
  31.     }
  32.  
  33.     A(std::string s): s(s) {
  34.         std::cout << "A(std::string s): " << s << std::endl;
  35.     }
  36.  
  37. #ifdef ENABLE_COPY_CTOR
  38.     A(const A& other) {
  39.         std::cout << "A(const A& other): " << s << std::endl;
  40.         this->s = other.s;
  41.     }
  42. #else
  43.     #if CXX_VER > 03
  44.         A(const A& other) = delete;
  45.     #endif
  46. #endif
  47.  
  48. #if defined(ENABLE_MOVE_CTOR) && CXX_VER > 03
  49.     A(A&& other) {
  50.         std::cout << "A(A&& other)" << std::endl;
  51.         this->s = other.s;
  52.         other.s = "";
  53.     }
  54. #else
  55.     #if CXX_VER > 03
  56.         A(A&& other) = delete;
  57.     #endif
  58. #endif
  59.     std::string s;
  60. };
  61.  
  62. A f(bool c = false) {
  63.     //return c ? A("hello") : A("hello2");
  64.     return A("hello");
  65. }
  66.  
  67. int main() {
  68.     A a = f();
  69.     std::cout << a.s << std::endl;
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement