Skip to content

Instantly share code, notes, and snippets.

@parsa
Created February 19, 2018 19:45
Show Gist options
  • Select an option

  • Save parsa/bf31f70af02069b511f78b2e1d0768ea to your computer and use it in GitHub Desktop.

Select an option

Save parsa/bf31f70af02069b511f78b2e1d0768ea to your computer and use it in GitHub Desktop.
Constructors Demo
#include <iostream>
struct A
{
//A() = delete;
A()
{
std::cout << "A::A()\n";
}
A(int)
{
std::cout << "A::A(int)\n";
}
~A()
{
std::cout << "A::~A()\n";
}
A(const A&)
{
std::cout << "A::A(const A&)\n";
}
A(A&&)
{
std::cout << "A::A(A&&)\n";
}
A& operator= (const A&)
{
std::cout << "A::operator= (const A&)\n";
return *this;
}
A& operator= (A&&)
{
std::cout << "A::operator= (A&&)\n";
return *this;
}
};
struct B
{
B()
{
std::cout << "B::B()\n";
}
B(const A& a)
{
std::cout << "B::B(const A&)\n";
value = a;
}
B(A&& a)
{
std::cout << "B::B(const A&)\n";
value = std::move(a);
}
~B()
{
std::cout << "B::~B()\n";
}
B(const B& b)
{
std::cout << "B::B(const B&)\n";
value = b.value;
}
B(B&& b)
{
std::cout << "B::B(B&&)\n";
value = std::move(b.value);
}
B& operator= (const B& b)
{
std::cout << "B::operator= (const B&)\n";
value = b.value;
return *this;
}
B& operator= (B&& b)
{
std::cout << "B::operator= (B&&)\n";
value = std::move(b.value);
return *this;
}
private:
A value;
};
int main()
{
std::cout << "Case 1:\n";
{
auto x = B(A(1));
}
std::cout << "\nCase 2:\n";
{
A a(1);
B b(a);
}
std::cout << "\nCase 3:\n";
{
A a(1);
B b(std::move(a));
}
std::cout << "\nCase 4:\n";
{
B b(A{1});
}
std::cout << "\nCase 5:\n";
{
A a{A{A{1}}};
}
std::cout << "\nCase 6:\n";
{
B b;
}
}
/*
Output:
Start
Case 1:
A::A(int)
A::A()
B::B(const A&)
A::operator= (A&&)
A::~A()
B::~B()
A::~A()
Case 2:
A::A(int)
A::A()
B::B(const A&)
A::operator= (const A&)
B::~B()
A::~A()
A::~A()
Case 3:
A::A(int)
A::A()
B::B(const A&)
A::operator= (A&&)
B::~B()
A::~A()
A::~A()
Case 4:
A::A(int)
A::A()
B::B(const A&)
A::operator= (A&&)
A::~A()
B::~B()
A::~A()
Case 5:
A::A(int)
A::~A()
Case 6:
A::A()
B::B()
B::~B()
A::~A()
0
Finish
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment