繁体   English   中英

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

[英]Getting value of C++ list iterator problem

我有这样的代码:

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

function,它返回指向列表中第一个窗口信息结构的迭代器的指针:

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 

您可能会问为什么第一个代码有效? 它只是靠运气工作:碰巧该代码编译器生成的代码未使用迭代器使用的堆栈 memory。 在第二个示例中,编译器可能会生成不同的代码,其中使用并更改了迭代器 memory。

暂无
暂无

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

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