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

I am curious if Rule 7-5-3 is only applicable when a reference to a parameter that is passed by const reference is returned from a function, but also if that reference is stored and then used later.

The rationale of the rule states that "It is implementation-defined behaviour whether the reference parameter is a temporary object or a reference to the parameter." and then goes on to say that a temporary object will be destroyed when the function returns and that using an object after its destruction will lead to undefined behaviour.

Considering the following code:
Code:
class TestConstRef
{
public:
  TestConstRef(const T& aT) : mT(aT) {}
  ~TestConstRef() {}

private:
  const T& mT;
};

If I understand the rule correctly, the parameter aT could be a temporary object which will be destroyed when the constructor exits and when the member reference mT is used later, the temporary object that it refers to may (depending on the implementation) no longer exist and that will lead to undefined behaviour.

Could I ask:
  • Is this understanding correct?
  • Is so, why is only returning the reference explicitly covered by the rules, and not storing the reference as in the code snippet above?
<t></t>
Reply


Messages In This Thread

Forum Jump:


Users browsing this thread: 2 Guest(s)