c++ - References not giving expected result -


if run below code, outputs,

key: 3, value: 4 key: 32767, value: 1971892984 

i created example mistake, know kv class should not storing references in member variables. having trouble explaining result.

i have expected key_ , value_ alias i , j on stack. should still valid when passed cout << first since haven't been taken off stack yet. can't guess reason why output different. implementation-specific detail i'm seeing? or there deeper here understand?

#include <iostream>  using namespace std;  template <typename k, typename v> class kv { public:     kv(): key_(), value_() {}     kv(k& key, v& value): key_(key), value_(value) {}      k key() const { return key_; }     v value() const { return value_; }   private:     k& key_;     v& value_; };  template <typename t, typename u> ostream& operator<<(std::ostream &strm, const kv<t, u> &a) {     cout << "key: " << a.key() << ", value: " << a.value() << endl;     strm << "key: " << a.key() << ", value: " << a.value() << endl; }  template <typename t, class u> kv<t, u> make_kv(t t, u u) {     kv<t,u> kv(t, u);     return kv; }  int main() {     int = 3, j = 4;     kv<int, int> first = make_kv(i, j);     cout << first;      return 0; } 

you have dangling references, , therefore undefined behaviour. reason references store in make_kv references local objects, scope function itself:

template <typename t, class u> kv<t, u> make_kv(t t, u u) {     kv<t,u> kv(t, u);     return kv; }  // t, u end here!!! 

you fix problem modifying make_kv take references:

template <typename t, class u> kv<t, u> make_kv(t& t, u& u) {     kv<t,u> kv(t, u);     return kv; } 

note: must make sure understand copy , assignment semantics of types hold references. might idea make references const limit scope of unintended behaviour.


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -