Skip to content

Instantly share code, notes, and snippets.

@loic-sharma
Last active September 19, 2023 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loic-sharma/e1d490d35d9fcad7bf619d24badd6e4e to your computer and use it in GitHub Desktop.
Save loic-sharma/e1d490d35d9fcad7bf619d24badd6e4e to your computer and use it in GitHub Desktop.
#include <iostream>
class Foo {
public:
std::unique_ptr<int> data;
Foo(int d) {
data = std::make_unique<int>(d);
std::cout << "Constructor called" << std::endl;
};
Foo(const Foo& other) {
data = std::make_unique<int>(*other.data);
std::cout << "Copy constructor called" << std::endl;
}
Foo(Foo&& other) noexcept {
data = std::move(other.data);
std::cout << "Move constructor called" << std::endl;
}
};
class Bar {
public:
Foo foo_;
Bar(const Foo& foo) : foo_(foo) {}
};
class Baz {
public:
Foo foo_;
Baz(Foo foo) : foo_(std::move(foo)) {}
};
int main() {
std::cout << "Creating foo..." << std::endl;
Foo foo{ 1 };
std::cout << std::endl;
std::cout << "Creating bar..." << std::endl;
Bar bar{ foo };
std::cout << std::endl;
std::cout << "Creating baz..." << std::endl;
Baz baz{ std::move(foo) };
return 0;
}
Creating foo...
Constructor called
Creating bar...
Copy constructor called
Creating baz...
Move constructor called
Move constructor called
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment