Skip to content

Instantly share code, notes, and snippets.

@devanshdalal
Last active November 11, 2019 17:36
Show Gist options
  • Save devanshdalal/48d7b686248556c655dbefac25b566c7 to your computer and use it in GitHub Desktop.
Save devanshdalal/48d7b686248556c655dbefac25b566c7 to your computer and use it in GitHub Desktop.
understanding move semantics
#include <iostream>
#include <cstring>
class Foo
{
public:
Foo(): a(new char[10])
{
std::cout << "Contructor\n";
}
Foo(const char* v): a(new char[10])
{
std::cout << "Non-trivial Contructor\n";
std::strncpy(a, v, 10);
}
Foo(Foo&& rvalue) : a(rvalue.a)
{
std::cout << "Move Contructor\n";
// a = rvalue.a;
rvalue.a = nullptr;
}
Foo& operator=(Foo&& rvalue)
{
std::cout << "Move Assignment\n";
{
std::cout << "Deleting a in MAO\n";
delete a;
}
a = rvalue.a;
rvalue.a = nullptr;
return *this;
}
Foo(const Foo& other): a(new char[10]) {
std::cout << "Copy Contructor\n";
for (int i=0; i < 10; ++i) {
a[i] = other.a[i];
}
}
Foo operator=(const Foo& other) {
std::cout << "Copy Assignment\n";
a = new char[10];
std::cout << "Copy Contructor\n";
for (int i=0; i < 10; ++i) {
a[i] = other.a[i];
}
return *this;
}
~Foo()
{
if (a != nullptr) {
std::cout << "deleting a\n";
delete a;
} else {
std::cout << "a is nullptr\n";
}
std::cout << "foo deconstructed" << std::endl;
}
void speak()
{
std::cout << "i'm foo" << std::endl;
}
char * a;
};
int main()
{
std::cout << "1" << std::endl;
Foo foo(std::forward<Foo&&>(Foo("dev"))); // done to avoid copy elision
std::cout << "2" << std::endl;
foo.speak();
std::cout << "5" << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment