Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rule 7-5-3 and storing a reference for later use
#2
Interesting point.

I think the rule refers to chapter 5.2.2 paragraph 5 of ISO/IEC 14882:2003:

Quote:Where a parameter is of const reference type a temporary object is introduced if
needed (7.1.5, 2.13, 2.13.4, 8.3.4, 12.2). In addition, it is possible to modify the values of nonconstant
objects through pointer parameters.

However, you can make the same mistake by storing a reference to a temporary object:

Code:
class cFoo
{
public:
  cFoo(const int& arg) : ref(arg){}
  const int& get(void) const{return ref;}
private:
  const int& ref;
};

const cFoo& init(void){return *(new cFoo(2));}

int main(void)
{
  const cFoo& f = init();// creates temporary int 2
  int x = 5;// overwrites temporary int
  return f.get() + x;// program returns 5 (not 7) - ignore the memory leak:)
}
<t></t>
Reply


Messages In This Thread

Forum Jump:


Users browsing this thread: 6 Guest(s)