c++ - Reference class member (was) causing undefined behavior -


i'm attempting make class holds class 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 lack of detail won't bug (i know guys see full code, reduced because if isn't problem it's else have figure out. post more/the rest if needed), had code similar this, , weird unicode characters when doing involving ref. once changed ref non-reference, weird undefined behavior went away.

i'd know if above legal future reference. know in scenario i'm not saving whole lot of memory referencing class (since it's copying pointers, right?), feel necessary in future.

thanks in advance.

there major issue code: constructor takes parameter value, means reference refers temporary object. after constructor call, left dangling reference.

you need initialize reference valid object. can making constructor parameter reference:

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

then

example e; example2 e2(e); // e2.ref , e same object 

note: must make sure understand semantics of reference use this. reference isn't "like pointer". alias 1 , 1 existing object. unless need referential semantics, should store object:

class example2 { public:     example2(const example& to_be_initialized) : ex(to_be_initialized) { }  private:     example ex; }; 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -