Skip to content

Instantly share code, notes, and snippets.

@wilhelmtell
Last active August 29, 2015 14:18
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 wilhelmtell/490aad572f864c83edd6 to your computer and use it in GitHub Desktop.
Save wilhelmtell/490aad572f864c83edd6 to your computer and use it in GitHub Desktop.
Extract responsibility for exclusivity in a RAII class?
#include <utility>
#include <iostream>
struct exclusive {
exclusive() : o{true} { std::cout << this << " exclusive init\n"; }
~exclusive() {
if(owning())
std::cout << this << " exclusive cleanup\n";
else
std::cout << this << " exclusive no cleanup\n";
}
exclusive(exclusive const&) = delete;
exclusive& operator=(exclusive const&) = delete;
exclusive(exclusive&& rhs) : o{std::move(rhs.o)} {
rhs.o = false;
std::cout << this << " exclusive move-init\n";
}
exclusive& operator=(exclusive&& rhs) {
std::cout << this << " exclusive move-assign\n";
o = rhs.o;
rhs.o = false;
return *this;
}
bool owning() const { return o; }
private:
bool o;
};
struct foo {
foo() { std::cout << this << " foo init\n"; }
foo(foo&&) = default;
foo& operator=(foo&&) = default;
~foo() {
if(x.owning())
std::cout << this << " foo cleanup\n";
else
std::cout << this << " no foo cleanup\n";
}
private:
exclusive x;
};
int main(int /*argc*/, char* /*argv*/ []) {
std::cout << "[](foo) {}(foo{});\n";
[](foo) {}(foo{});
{
std::cout << "\nfoo f{};\n[](foo) {}(std::move(f));\n";
foo f{};
[](foo) {}(std::move(f));
}
{
// should not compile:
// std::cout << "\nfoo const f{};\n[](foo) {}(std::move(f));\n";
// foo const f{};
// [](foo) {}(std::move(f));
}
{
std::cout << "\nfoo f{};\n[](foo&) {}(f);\n";
foo f{};
[](foo&) {}(f);
}
{
std::cout << "\nfoo f{};\n[](foo&&) {}(std::move(f));\n";
foo f{};
[](foo&&) {}(std::move(f));
}
{
std::cout << "\nfoo const f{};\n[](foo const&) {}(f);\n";
foo const f{};
[](foo const&) {}(f);
}
{
std::cout << "\nfoo f{};\n[](foo const&) {}(f);\n";
foo f{};
[](foo const&) {}(f);
}
{
std::cout << "\nfoo f{};\n[](foo const&&) {}(std::move(f));\n";
foo f{};
[](foo const&&) {}(std::move(f));
}
{
std::cout << "\nfoo const f{};\n[](foo const&&) {}(std::move(f));\n";
foo const f{};
[](foo const&&) {}(std::move(f));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment