0

I'm writing a C++ program which should continuously write to a text file inside an OnIdle event loop (BTW, I'm using wxWidgets -3.0.3 and Visual Studio 17). For this purpose, I'm creating a TextOutputStream as described in the code below inside GetData().

Here gui_magsens->GetFilePath() simply gets a file path from a wxFilePickerCtrl and ActivateDataLoop(true) triggers the OnIdle loop. Now, what I would like to have is a global reference to my tos so that I can use it inside the OnIdle loop without having to create it (and close it) every iteration(not efficient and leads me to unhandled exceptions). What is the best (or cleanest) way to achieve this? What I have found so far is that you could use a pointer to the stream (as shown below), which compiles fine, but throws me a "read access violation" exception(apparently expected as the pointer points to an already "dead" stream). Also, is there a neat workaround without using pointers?

//----main.h----//

//...bunch of variables and functions
wxFileOutputStream* pFos;
wxTextOutputStream* pTos;

//---main.cpp----//

void wxMagSens::GetData()
{       
//create stream
wxString f_path = gui_magsens->GetFilePath();
wxFileOutputStream fos(f_path);
wxTextOutputStream tos(fos, wxEOL_NATIVE, wxConvUTF8); 
//ptrs
pFos = &fos;
pTos = &tos;
ActivateDataLoop(true); 
} 

void wxMagSens::OnIdleDataLoop(wxIdleEvent & evt)
{           
  //write to file
  pTos->WriteDouble(some_double);//Here's the exception
  //etc...
}

int wxMagSens::OnExit()
{
//USBInterface.USBClose();
if(pFos->IsOk()){ pFos->Close();}   
return 0;
}
  • make references (not pointers) your default when you dont want a copy, it will make your life easier – 463035818_is_not_an_ai Aug 30 '17 at 14:08
  • btw your streams live in the scope of the `GetData` functions and pointers to them will be invalid outside of `GetData`. You need to keep them alive as long as you want to use them – 463035818_is_not_an_ai Aug 30 '17 at 14:09
  • this is completely unrelated, but same problem: https://stackoverflow.com/questions/45959875/method-of-super-class-called-when-super-has-a-str-attr-instance-of-sub-is-crea/45959986?noredirect=1#comment78880266_45959986 – 463035818_is_not_an_ai Aug 30 '17 at 14:11
  • That is what c++ class members are designed for. – perencia Aug 30 '17 at 14:40
  • Thanks guys. That sufficed. Just wanted to know what the "right" way was. I was already trying to use a reference but was running into problems using "new Whatever()". Now it works the way I want. however it gives me some memory leaks when I close it(guess it comes from new). I checked this post: https://stackoverflow.com/questions/8544090/detected-memory-leaks, went to the line causing the problem and there's a comment telling that you should live with this leak as it is unlikely to happen. Are these leaks "normal"? Btw, I tried to explicitly destroy the objects but it still throws the same. – g_scanon_b Aug 30 '17 at 16:53

0 Answers0