简体   繁体   English

获取 C++ 列表迭代器问题的值

[英]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: function,它返回指向列表中第一个窗口信息结构的迭代器的指针:

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.您不应返回指向迭代器的指针,因为它在 windowGet() 调用后将无效。 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.它只是靠运气工作:碰巧该代码编译器生成的代码未使用迭代器使用的堆栈 memory。 In second example compiler may generate a different code in which the iterator memory was used and changed.在第二个示例中,编译器可能会生成不同的代码,其中使用并更改了迭代器 memory。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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