Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rule 7-5-3 and storing a reference for later use
#3
I am also concerned about the following type of snippet:
Code:
#include

class TestConstRef
{
public:
  TestConstRef(const int32_t& aInt) : mInt(aInt) {}
  ~TestConstRef() {}

private:
  const int32_t& mInt;
};

int main(void)
{
  const double aDouble = 45.3;
  const TestConstRef constRef(aDouble); // Temporary int32_t is created here
}

The line where the temporary int32_t is created is perfectly legal code, but the reference to it will be lost when the constructor exits.
However, the compiler will not warn you whether a temporary is created or not.

So, unless you have some other way to ensure absolutely that a temporary is not created for this sort of example, you could end up with a reference to a temporary.

Furthermore, the MISRA rule seems to suggest that temporaries can be introduced on an implementation-defined basis.

This seems to be borne out by the chapter 5.2.2 paragraph 5 of ISO/IEC 14882:2003 mentioned - which states that a temporary object is introduced "if needed". It does not specify what "if needed" means - so could this not vary system-by-system, such that even if you inspect the code and decide for yourself that temporaries are not needed, the compiler might decide otherwise?
<t></t>
Reply


Messages In This Thread

Forum Jump:


Users browsing this thread: 2 Guest(s)