2015-02-06 61 views
0

我寫簡單的代碼與vs2013和它的作品奇:線程例程函數中未調用局部變量析構函數嗎?

#include <Windows.h> 
#include <process.h> 
#include <stdio.h> 
#include <cstdint> 
#include <tchar.h> 

class A 
{ 
public: 
    explicit A(uint8_t byte) : mByte(byte) {} 
    ~A() { _tprintf(_T("A::~A(%x)\n"), mByte); } 
private: 
    uint8_t mByte; 
}; 

unsigned WINAPI threadRoutine(void*) 
{ 
    A a0(0x41); 
    _endthreadex(0); 
    return 0; 
} 

int _tmain(int argc, TCHAR *argv[]) 
{ 
    HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, threadRoutine, NULL, 0, NULL); 
    WaitForSingleObject(hThread, INFINITE); 
    CloseHandle(hThread); 
    return 0; 
} 

輸出是空的,所以這意味着A-析構函數的局部變量A0沒有被引用?

我的代碼裏面有一些錯誤嗎?

如果函數返回後未調用局部變量析構函數,如何維護RAII內部的線程例程函數?

+3

你並不需要調用'_endthreadex()'明確。只要讓函數正常終止即可。 – 2015-02-06 13:26:12

+0

我建議你使用'std :: thread'而不是編譯器特定的方法。 – nvoigt 2015-02-06 13:29:28

+0

謝謝,它現在可行!我沒有仔細閱讀_endthreadex手冊! – kvv 2015-02-06 13:31:28

回答

5

_endthread_endthreadex在線程從傳遞給_beginthread_beginthreadex的例程返回後自動調用。

可以顯式調用它們來結束一個線程,但你不必。

調用_endthread_endthreadex會導致掛起的C++析構函數在它們終止的線程上不被調用。

來源:MSDN