samedi 28 mars 2015

Reference class member (was) causing undefined behavior


I'm attempting to make a class which holds another class as a reference (private member).



class example{
private:
std::vector<char> chars;
};

class example2{
example2(example to_be_initialized) :ref(to_be_initialized) { }
private:
example& ref;
};


Hopefully the lack of detail won't bug anyone (I know you guys like to see the full code, but I reduced it because if this isn't the problem it's something else I have to figure out. But I will post more/the rest if needed), but I had code very similar to this, and I would get weird unicode characters when doing anything involving ref. once I changed ref to a non-reference, all the weird undefined behavior went away.


I'd like to know if the above is legal simply for future reference. I know in this scenario I'm not saving a whole lot of memory by referencing the class (since it's just copying pointers, right?), but I feel something like this would be necessary in the future.


Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire