Skip to content

Instantly share code, notes, and snippets.

@jwpeterson
Created June 6, 2018 20:04
Show Gist options
  • Select an option

  • Save jwpeterson/6b60a7f972c703e322cc75b4b2fedcf1 to your computer and use it in GitHub Desktop.

Select an option

Save jwpeterson/6b60a7f972c703e322cc75b4b2fedcf1 to your computer and use it in GitHub Desktop.
Defaulted destructors inhibit move constructor generation
#include <iostream>
#include <vector>
struct S
{
S(const S&) { std::cout << "Copied an S\n"; }
S(S&&) { std::cout << "Moved an S\n"; }
S() = default;
};
// This class declares _none_ of the "special" functions, so the
// compiler generates default versions of all of them.
struct Movable
{
S s;
};
// The fact that this class declares a destructor (even an =default
// one) means that the compiler will _not_ generate a move ctor for
// it, the way that it will for the "Movable" class.
struct NotMovable
{
S s;
~NotMovable() = default;
};
// This class has all 5 "special" functions explicitly defaulted. This
// allows the compiler to move an S in the usage below.
// See also: https://stackoverflow.com/questions/4782757/rule-of-three-becomes-rule-of-five-with-c11
struct AllDefaulted
{
S s;
// A defualted constructor, since we need it for this specific
// problem. This is not generally considered one of the "rule of 5"
// functions.
AllDefaulted() = default;
// The "rule of 5" functions.
AllDefaulted(const AllDefaulted&) = default;
AllDefaulted(AllDefaulted&&) = default;
AllDefaulted& operator=(const AllDefaulted&) = default;
AllDefaulted& operator=(AllDefaulted&&) = default;
~AllDefaulted() = default;
};
int main(int argc, char * argv[])
{
std::vector<Movable> v1;
std::cout << "Movable(): ";
v1.push_back(Movable()); // Will move an S.
std::vector<NotMovable> v2;
std::cout << "NotMovable(): ";
v2.push_back(NotMovable()); // Will copy an S.
std::vector<AllDefaulted> v3;
std::cout << "AllDefaulted: ";
v3.push_back(AllDefaulted()); // Will move an S.
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment