Skip to content

Instantly share code, notes, and snippets.

@jstaursky
Last active July 13, 2021 00:55
Show Gist options
  • Save jstaursky/32825de069ac0ffd0b5c34646bd7eaa8 to your computer and use it in GitHub Desktop.
Save jstaursky/32825de069ac0ffd0b5c34646bd7eaa8 to your computer and use it in GitHub Desktop.
move semantics tutorial program from https://www.youtube.com/watch?v=ehMg6zvXuMY "The Cherno"
#include <iostream>
#include <cstring>
class String
{
public:
String () = default;
String (const char* string)
{
printf("Created!\n");
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
{
printf ("Moved!\n");
m_Size = other.m_Size;
m_Data = other.m_Data;
other.m_Size = 0;
other.m_Data = nullptr;
}
~String()
{
printf("Destroyed!\n");
delete m_Data;
}
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)
: m_Name(std::move(name))
{
}
void PrintName()
{
m_Name.Print();
}
private:
String m_Name;
};
int main(int argc, char *argv[])
{
Entity entity(String("foo")); // Could have also just used "foo" which would do an implicit conversion.
entity.PrintName();
std::cin.get();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment