returning address of local variable or temporary

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • curious2007
    New Member
    • Jun 2007
    • 71

    returning address of local variable or temporary

    Hello Everyone,

    I had this code working on DEV C++. But now, it does not work in Visual C++ Exress. Here is the code:
    [code=cpp]
    template <class V, class AI, class I, class S>
    const V& AssocArray<V, AI, I, S>::operator [] (const AI& index) const
    {
    const_iterator it = internal_array. find(index);

    V mapIndex = (*it).second;
    return mapIndex;

    }[/code]

    I get the following warning:

    warning C4172: returning address of local variable or temporary

    It is not clear to me what this means. I would appreciate any help.
    Last edited by sicarie; Jul 18 '07, 05:40 PM. Reason: Please use [code=cpp] and [/code] tags around your code.
  • sicarie
    Recognized Expert Specialist
    • Nov 2006
    • 4677

    #2
    Please make sure you use code tags (they're in the box to the right when you are creating/replying to a thread.

    Comment

    • Darryl
      New Member
      • May 2007
      • 86

      #3
      The error is right, you are returning a local/temp variable. Why don't you return (*it).second; directly?

      Comment

      • curious2007
        New Member
        • Jun 2007
        • 71

        #4
        OK, thanks. Do you know why is this a reason for warning?

        Comment

        • Darryl
          New Member
          • May 2007
          • 86

          #5
          Originally posted by curious2007
          OK, thanks. Do you know why is this a reason for warning?
          Because when the local variable (MapIndex in your case) goes out of scope (when the function returns) it is destroyed and therefore no longer valid.

          Comment

          Working...