Creating a class friend

EDIT: Looks like I'm completely misinformed. Close this topic. G.

For recording, the following compilation and work:

class ForeverAlone { private: int m_friends; HANDLE m_handle; public: ForeverAlone() { m_handle = CreateThread(NULL, 0, &ForeverAlone::SadThread, reinterpret_cast<void*>(this), 0, NULL); } ~ForeverAlone() { if (m_handle != NULL) CloseHandle(m_handle); } protected: static unsigned long WINAPI SadThread(void* param) { ForeverAlone* thisObject = reinterpret_cast<ForeverAlone*>(param); // is there any way for me to access: thisObject->m_friends; } }; 

The original question: I have a static protected thread method with which I pass an object. Is there any way to create a friend class so that I can access its private members?

+3
source share
2 answers

All class methods, static or not, are automatically "friends" of the class. A friend is used to access external functions and classes of a class. A class is always its own "friend."

+11
source

Do it:

 extern "c" DWORD __stdcall CInterfaceSadThread(LPVOID lpThreadParameter); class ForeverAlone { private: int m_friends; HANDLE m_handle; public: ForeverAlone() { m_handle = CreateThread(NULL, 0, &CInterfaceSadThread, // // You may get arguments about using static_cast here // I still prefer reinterpret_cast as it makes it stick out // Thus I check it more carefully when I see it. // For this situation it works correctly // As casting to void* and back to the original are guaranteed. reinterpret_cast<void*>(this), 0, NULL); } ~ForeverAlone() { if (m_handle != NULL) CloseHandle(m_handle) } protected: friend DWORD CInterfaceSadThread(LPVOID lpThreadParameter); DWORD WINAPI SadThread() { // Do Stuff here // Note: Just because you get here does not mean that the object is finished // initializing. The parent thread may have been suspended after this // one was created. Thus checking the state of member variables at this // point is dangerous unless you can guarantee that construction has finished return result; } }; 

Then in the callback, just access your function;

 extern "c" DWORD __stdcall CInterfaceSadThread(LPVOID lpThreadParameter) { // Note: You can only cast back to ForeverAlone* so be carefull // Hence I use reinterpret_cast as this forces me to double check. ForeverAlone* alone = reinterpret_cast<ForeverAlone*>(lpThreadParameter); return alone->SadThread(); } 
+1
source

Source: https://habr.com/ru/post/973491/


All Articles