Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <memory>
- class String
- {
- public:
- String() = default;
- String(const char* string)
- {
- printf("Created!\n"); // 'f' at the end of the function name refers to “formatted”,
- // indicating that the function requires a format string in addition to the values to be printed.
- m_Size = strlen(string);
- m_Data = new char[m_Size];
- memcpy(m_Data, string, m_Size);
- }
- String(const String& other)
- {
- printf("Copied!\n");
- m_Size = other.m_Size;
- m_Data = new char[m_Size];
- memcpy(m_Data, other.m_Data, m_Size);
- }
- String(String&& other) noexcept // Move constructor, means Cherno in Entity entity("Cherno"); becomes temporary
- {
- printf("Moved!\n");
- m_Size = other.m_Size;
- m_Data = other.m_Data; // taking the pointer to m_Data (existing buffer in og string) and saying
- // char* m_Data; points to the same data
- // Can't end move constructor here, have to take care of the other string instance who you take control of/steal from
- // We make a hollow object doing this, shallow copy with rewired pointers basically
- other.m_Size = 0;
- other.m_Data = nullptr;
- }
- String& operator=(String&& other) noexcept
- { // Not constructing new object like in the move constructor above, we're moving another object into this current object
- // Meaning we need to overwrite the current object
- printf("Moved!\n");
- if (this != &other) // Making sure we can't move the current object into itself. AKA same object.
- {
- delete[] m_Data; // Have to add this because we're about to move another object into ourselves and the old data has to be deleted
- m_Size = other.m_Size;
- m_Data = other.m_Data;
- other.m_Size = 0;
- other.m_Data = nullptr;
- }
- return *this; // reference to current object
- }
- ~String()
- {
- printf("Destroyed\n");
- delete[] m_Data; // Done with [] since m_Data = new char[m_Size]
- }
- void Print()
- {
- for (uint32_t i = 0; i < m_Size; i++)
- printf("%c", m_Data[i]);
- printf("\n");
- }
- private:
- char* m_Data;
- uint32_t m_Size;
- };
- class Entity
- {
- public:
- Entity(const String& name)
- : m_Name(name)
- {
- }
- Entity(String&& name) // Should be called instead of other if an rvalue is used
- : m_Name(std::move(name)) // Name is "Cherno" from entity below
- {
- }
- void PrintName()
- {
- m_Name.Print();
- }
- private:
- String m_Name;
- };
- int main()
- {
- //Entity entity("Cherno");
- //entity.PrintName();
- String apple = "Apple";
- String dest;
- std::cout << "Apple: ";
- apple.Print();
- std::cout << "Dest: ";
- dest.Print();
- // Moves contents of apple into destination and leave apple in a valid state
- dest = std::move(apple); // Have to do this way, not dest = apple;
- std::cout << "Apple: ";
- apple.Print();
- std::cout << "Dest: ";
- dest.Print();
- std::cin.get();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement