Skip to content

Instantly share code, notes, and snippets.

@LarryRuane
Created January 31, 2023 15:38
Show Gist options
  • Save LarryRuane/45c63fb99d8600be38bddb893073a4e5 to your computer and use it in GitHub Desktop.
Save LarryRuane/45c63fb99d8600be38bddb893073a4e5 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string.h>
int line;
class String {
public:
char* m_buffer;
size_t m_size;
// copy cons
String(const char* string) {
m_size = strlen(string);
m_buffer = new char[m_size+1];
strcpy(m_buffer, string);
std::cout << line << " constructor from char* " << m_buffer << " " << intptr_t(m_buffer) << "\n";
}
String(const String& other) {
m_size = other.m_size;
m_buffer = new char[m_size+1];
strcpy(m_buffer, other.m_buffer);
std::cout << line << " constructor from other " << m_buffer << " " << intptr_t(m_buffer) << "\n";
}
String(String&& other) {
m_size = other.m_size;
m_buffer = other.m_buffer; // copy just the pointer!
other.m_size = 0;
other.m_buffer = nullptr;
std::cout << line << " move from other " << m_buffer << " " << intptr_t(m_buffer) << "\n";
}
String() {}
~String() {
std::cout << line << " delete " << m_buffer << " " << intptr_t(m_buffer) << "\n";
delete[] m_buffer;
}
};
void f(const String& s) {
String copy{s};
std::cout << line << " f(" << copy.m_buffer << ")\n";
}
int main()
{
line = __LINE__; String s = "hello";
line = __LINE__; String a{"hi"};
line = __LINE__; String b = s;
line = __LINE__; String c{s};
line = __LINE__; f(String("bye"));
line = __LINE__; f(std::move(String("bye")));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment