Код: Выделить всё
#include
#include
template
class NullableOffsetPtr
{
public:
NullableOffsetPtr(T const* ptr) :
offset_{
ptr == nullptr ? std::ptrdiff_t{1} : reinterpret_cast(ptr) - reinterpret_cast(this)}
{
}
T* get()
{
return offset_ == 1 ? nullptr : reinterpret_cast(reinterpret_cast(this) + offset_);
}
private:
std::ptrdiff_t offset_; // Using units of bytes, as alignments of *this and *ptr may not match.
};
class Sample
{
};
int main(int argc, char* argv[])
{
Sample sample;
NullableOffsetPtr ptr{&sample};
std::cout
Подробнее здесь: [url]https://stackoverflow.com/questions/78427986/what-is-undefined-behaviour-in-these-pointer-conversions[/url]