Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@nil-ableton
Last active March 29, 2017 04:51
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 nil-ableton/6925d7e4f55a250f828e9a573f9320e7 to your computer and use it in GitHub Desktop.
Save nil-ableton/6925d7e4f55a250f828e9a573f9320e7 to your computer and use it in GitHub Desktop.
self reference and copy ability / movability
#include <cstddef>
#include <cstdint>
#include <cstdio>
// ptr_to_buffer make this struct not a regular type, i.e.
// not trivially copyable/moveable
struct StructA {
char* const ptr_to_buffer = buffer; // dependency to representation
size_t const buffer_size = sizeof buffer;
char buffer[64];
};
static bool valid(StructA const& x)
{
return x.ptr_to_buffer == x.buffer;
}
static void print(StructA const& x)
{
std::printf("%s",
valid(x) ? "// is valid "
: "// is INVALID (representation moved) ");
std::printf("{\n");
std::printf(" buffer = %zu;\n", intptr_t(x.buffer));
std::printf(" buffer_size = %zu;\n", x.buffer_size);
std::printf(" ptr_to_buffer = %zu;\n", intptr_t(x.ptr_to_buffer));
std::printf("}\n");
}
int main(int, char **)
{
StructA b = {};
StructA a = b; // there ought to be maybe a warning here no?
printf("a: "); print(a);
printf("b: "); print(b);
auto c = StructA{};
printf("c: "); print(c);
return 0;
};
@nil-ableton
Copy link
Author

$ clang++ -std=c++11 -O3 -Wall -Wextra -Werror -Weverything -Wno-c++98-compat-pedantic  -fsanitize=address,undefined self_reference_monster.cpp -o self_reference && ./self_reference 

a: // is INVALID (representation moved) {
    buffer = 140734543575456;
    buffer_size = 64;
    ptr_to_buffer = 140734543575344;
}
b: // is valid {
    buffer = 140734543575344;
    buffer_size = 64;
    ptr_to_buffer = 140734543575344;
}
c: // is valid {
    buffer = 140734543575568;
    buffer_size = 64;
    ptr_to_buffer = 140734543575568;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment