c++ - How to modify values of reference std::pair? -


so question pretty simple, tho haven't been able find answer i'm asking here.

i curious know whether can return std:: pair reference function, , have calling function modify values. here's example of mean:

struct pairstruct {     using pairtype = std::pair<size_t, size_t>;      pairstruct() : m_pair(std::make_pair(0, 0)) {}      void modifyrefinternal() {         auto pair = getpairref();          std::cout << "start - first: " << pair.first << ", second: " << pair.second << "\n";         pair.first++;         pair.second++;         std::cout << "end - first: " << pair.first << ", second: " << pair.second << "\n";     }      void modifyptrinternal() {         auto pair = getpairptr();          std::cout << "start - first: " << pair->first << ", second: " << pair->second << "\n";         pair->first++;         pair->second++;         std::cout << "end - first: " << pair->first << ", second: " << pair->second << "\n";     }      pairtype &getpairref() {         return m_pair;     }      pairtype *getpairptr() {         return &m_pair;     }      pairtype m_pair; };  int main(int argc, char ** args) {     pairstruct *pairinst = new pairstruct;      // test reference     std::cout << "reference test.\n";     pairinst->modifyrefinternal();     std::cout << "\n";     pairinst->modifyrefinternal();      std::cout << "\n";      // test ptr     std::cout << "ptr test.\n";     pairinst->modifyptrinternal();     std::cout << "\n";     pairinst->modifyptrinternal();      delete pairinst;     return 0; } 

as expected when use pointer correctly modyfies values, not case when returning reference. here's output of program:

reference test. start - first: 0, second: 0 end - first: 1, second: 1  start - first: 0, second: 0 end - first: 1, second: 1  ptr test. start - first: 0, second: 0 end - first: 1, second: 1  start - first: 1, second: 1 end - first: 2, second: 2 

this going seem trivial, however, i'd know why can't use referenced pair in case. thanks!

with

auto pair = getpairref(); 

the variable pair deduced value, not reference.

you need explicitly make reference:

auto& pair = getpairref(); 

Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -