简体   繁体   中英

Getting value of C++ list iterator problem

I have code like this:

struct sWindowInfo {
    WNDPROC pPrevWndProc;
};
typedef std::list<sWindowInfo> windowsList;

And function, which returns pointer to iterator of first window-info struct in list:

windowsList::const_iterator* windowGet();

Code like this works fine:

if (windowsList::const_iterator* itr = windowGet())
{
    WNDPROC wndProc = (*itr)->pPrevWndProc;        
    return CallWindowProc(wndProc, hWnd, msg, wParam, lParam);
}

But if i try:

if (windowsList::const_iterator* itr = windowGet())
    return CallWindowProc((*itr)->pPrevWndProc, hWnd, msg, wParam, lParam);

Runtime error occurs and i see strange values in debugger. I don't understand, why? In my opinion this is identical code.

Both implementations are wrong. You should not return pointers to iterator since it will be invalid after windowGet() call. It is the same thing as doing this:

int* getInt()
{
    int a = 10;
    return &a;
}

int* a = getInt();


int v = *a ; // v may be 10 or may be not 

You may ask why first code is working? It is working just by luck: it happened that for that code compiler generates code that is not using the stack memory which was used by iterator. In second example compiler may generate a different code in which the iterator memory was used and changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM