fork download
  1. #include <vector>
  2. #include <iostream>
  3.  
  4. class String
  5. {
  6. public:
  7. //! default constructor
  8. String();
  9.  
  10. //! constructor taking C-style string i.e. a char array terminated with'\0'.
  11. explicit String(const char * const c);
  12.  
  13. //! copy constructor
  14. explicit String(const String& s);
  15.  
  16. //! move constructor
  17. String(String&& s) noexcept;
  18.  
  19. //! operator =
  20. String& operator = (const String& rhs);
  21.  
  22. //! move operator =
  23. String& operator = (String&& rhs) noexcept;
  24.  
  25. //! destructor
  26. ~String();
  27.  
  28. //! members
  29. char* begin() const { return elements; }
  30. char* end() const { return first_free; }
  31.  
  32. std::size_t size() const {return first_free - elements; }
  33. std::size_t capacity() const {return cap - elements; }
  34.  
  35. private:
  36.  
  37. //! data members
  38. char* elements;
  39. char* first_free;
  40. char* cap;
  41.  
  42. std::allocator<char> alloc;
  43.  
  44. //! utillities for big 3
  45. void free();
  46.  
  47. };
  48.  
  49. //! default constructor
  50. String::String():
  51. elements (nullptr),
  52. first_free (nullptr),
  53. cap (nullptr)
  54. {}
  55.  
  56. //! copy constructor
  57. String::String(const String &s)
  58. {
  59. char* newData = alloc.allocate(s.size());
  60. std::uninitialized_copy(s.begin(), s.end(), newData);
  61.  
  62. elements = newData;
  63. cap = first_free = newData + s.size();
  64.  
  65. std::cout << "Copy constructing......\n";
  66. }
  67.  
  68. //! move constructor
  69. String::String(String &&s) noexcept :
  70. elements(s.elements), first_free(s.first_free), cap(s.cap)
  71. {
  72. s.elements = s.first_free = s.cap = nullptr;
  73. std::cout << "Move constructing......\n";
  74. }
  75.  
  76. String::~String()
  77. {
  78. // leaky leaky
  79. }
  80.  
  81. String& String::operator = (String&& rhs) noexcept
  82. {
  83. String temp(rhs);
  84. std::swap(elements, temp.elements);
  85. std::swap(first_free, temp.first_free);
  86. std::swap(cap, temp.cap);
  87. return *this;
  88. }
  89.  
  90. int main()
  91. {
  92. std::vector<String> v;
  93. String s;
  94. for (unsigned i = 0; i != 4; ++i)
  95. v.push_back(s);
  96.  
  97. return 0;
  98. }
  99.  
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Copy constructing......
Copy constructing......
Move constructing......
Copy constructing......
Move constructing......
Move constructing......
Copy constructing......