C++ (Qt)void CBigClass::SomeMethod( bool useSelection ) { .. int limit = useSelection ? mSelection.size() : mData.size(); auto dataIt = mData.begin(); auto selIt = mSelection.begin(); for (int i = 0; i < limit; ++i) { CData * dataPtr; if (useSelection) { dataPtr = *selIt; ++selIt; } else { dataPtr = &(*dataIt); ++dataIt; } ... }}
void CBigClass::SomeMethod( bool useSelection ) { .. CDataIt it(*this, useSelection); while (it.HasNext()) { CData & data = it.GetNext(); ....}
QSet<std::reference_wrapper<CData>>& mSelectionAsRefs() { static_assert(sizeof(CData*) == sizeof(std::reference_wrapper<CData>)); return reinterpret_cast<QSet<std::reference_wrapper<CData>>&>(mSelection);}
QSet<std::reference_wrapper<CData>>& mSelectionAsRefs(){ static_assert(sizeof(CData*) == sizeof(std::reference_wrapper<CData>)); QSet<CData*>* src = &mSelection; QSet<std::reference_wrapper<CData>>* alias; std::memcpy(&alias, &src, sizeof(alias)); // starts lifetime of alias as QSet<CData*>* return *alias;}
QSet<std::reference_wrapper<CData>>& mSelectionAsRefs(){ static_assert(sizeof(CData*) == sizeof(std::reference_wrapper<CData>)); QSet<CData*>* src = &mSelection; void* alias; std::memcpy(&alias, &src, sizeof(alias)); // starts lifetime of alias as QSet<CData*>* return *static_cast<QSet<std::reference_wrapper<CData>>*>(alias);}
QSet<std::reference_wrapper<CData>>& mSelectionAsRefs() { static_assert(sizeof(CData*) == sizeof(std::reference_wrapper<CData>)); return std::bit_cast<QSet<std::reference_wrapper<CData>>&>(mSelection);}
void* p; // declarationp = new int(5); // p begins its lifetime with dynamic type int*
int i;void* p; // declarationp = &i; // p begins its lifetime with dynamic type int*
C++ (Qt)using CDataRef = std::reference_wrapper<CData>;QSet<CDataRef>& SelectionAsRefs( void ) { static_assert(sizeof(CData*) == sizeof(CDataRef)); return *(QSet<CDataRef> *) &mSelection;}
#include <QSet>#include <iostream>using namespace std;typedef int CData;using CDataRef = reference_wrapper<CData>;QSet<CData*>* mSelection = new QSet<CData*>;QSet<CDataRef>*& SelectionAsRefs( void ){ static_assert(sizeof(CData*) == sizeof(CDataRef)); return *(QSet<CDataRef> **) &mSelection;}static QSet<CData*>* makeUB(QSet<CData*>** src, QSet<CDataRef>** alias){ static QSet<CData*> data = { new CData }; // set with one element *src = &data; *alias = nullptr; return *src; // what will be there: &data or nullptr?}int main(int, char *[]){ mSelection = makeUB(&mSelection, &SelectionAsRefs()); std::cout << (!mSelection ? "OK" : "UB") << std::endl;}