开发者

Getting value of C++ list iterator problem

I have code like this:

struct sWind开发者_运维问答owInfo {
    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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜