2

I have a static library that has a function such as:

bool CreateObject(Object*& Out_Object)
{
   thread_local static volatile Object obj = {};
   InitializeObject(&obj);
   if(obj.IsValid())
   {
     Out_Object = &obj;
     return(true);
   }
   return(false);
}

I want this function to manage a thread specific object for each thread that calls it by initializing the object and returning it.

What happens to the memory of obj here, is it located in the local thread storage or somewhere else and is this somewhat safe?

Edit: By safe, I mean 'what are the potential problems here that I'm not seeing?'

vlind
  • 629
  • 6
  • 16
  • This is not valid C. – Kerrek SB Aug 02 '16 at 18:37
  • tag removed, i forgot that I was using c++ keywords, thanks! – vlind Aug 02 '16 at 18:39
  • 1
    Off topic: `Object`'s constructor may be a better place to do initialization than an `InitializeObject` function. [You can get the whole RAII thing working for you.](https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization). Mind you this would require a bit more of a plumbing change--throwing an exception instead of `if(obj.IsValid())` -- but it looks like you're trying to make a thread local singleton. Give this a read: http://stackoverflow.com/questions/1008019/c-singleton-design-pattern – user4581301 Aug 02 '16 at 18:46
  • I'm trying to create a library that manages all its resources, objects and via a pimpl interface. I don't want the data on the heap and as such want it statically inside or outside, outside not being an option since the implementation isnt available to the interface and thus the user cannot send an object in to be modified. CreateObject returns a opaque handle from the library. – vlind Aug 02 '16 at 18:52
  • 1
    @vlind: I was more concerned about this weird syntax `*&`... :-) – Kerrek SB Aug 02 '16 at 19:06
  • Don't post images of text, less links thereof. Copy/paste the text - heck, that is even easier. – too honest for this site Aug 02 '16 at 19:07

0 Answers0