我有这样的代码:
struct sWindowInfo {
WNDPROC pPrevWndProc;
};
typedef std::list<sWindowInfo> windowsList;
还有函数,它返回指向列表中第一个窗口信息结构的迭代器的指针:
windowsList::const_iterator* windowGet();
像这样的代码工作正常:
if (windowsList::const_iterator* itr = windowGet())
{
WNDPROC wndProc = (*itr)->pPrevWndProc;
return CallWindowProc(wndProc, hWnd, msg, wParam, lParam);
}
但如果我尝试:
if (windowsList::const_iterator* itr = windowGet())
return CallWindowProc((*itr)->pPrevWndProc, hWnd, msg, wParam, lParam);
发生运行时错误,我在调试器中看到奇怪的值。 我不明白,为什么?在我看来,这是相同的代码。
最佳答案
两种实现都是错误的。您不应返回指向迭代器的指针,因为它在 windowGet() 调用后将无效。 这与这样做是一样的:
int* getInt()
{
int a = 10;
return &a;
}
int* a = getInt();
int v = *a ; // v may be 10 or may be not
您可能会问为什么第一个代码有效?它的工作完全靠运气:碰巧对于该代码,编译器生成的代码没有使用迭代器使用的堆栈内存。在第二个示例中,编译器可能会生成不同的代码,其中使用和更改了迭代器内存。
关于c++ - 获取C++列表迭代器问题的值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6755761/