Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

nil-ableton commented Mar 29, 2017

$ 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