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()
- {
- 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((String&&)name) // Copy made by doing m_Name(name), has to be the way on the left of this
- // We explicitly cast it to a temporary
- //In reality, you'd do m_Name(std::move(name)) instead for the code above
- {
- }
- void PrintName()
- {
- m_Name.Print();
- }
- private:
- String m_Name;
- };
- int main()
- {
- Entity entity("Cherno"); // Implicit version of Entity entity(String("Cherno"));
- entity.PrintName();
- std::cin.get();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement