-
DLL's and Strings
I've encountered a weird problem. I'm making a DLL to store some classes (with abstract interfaces). Each of the classes have a std::string ErrorMessage member and a std::string GetErrorMessage() method to keep track on possible errors.
Now every time I store the value from GetErrorMessage() in a std::string in my main prog (not the DLL) the program crashes after FreeLibrary() is called. However it only occurs if the string hasn't been destroyed yet.
My guess would be that when the string is returned it's not actually copied but pointing to the original string in the DLL class, so when FreeLibrary is called it points to invalid memory.
I also noticed if I do a string operation on the string, like:
Code:
std::string SomeError = Class->GetErrorMessage();
SomeError += "XXX";
It doesn't crash. Since the string is modified it gets its own memory and no longer points to the one inside the DLL.
I don't know of the inner workings of std::string, but this seemed reasonable considering the symptoms. So, my questin is is there an elegant solution to this? I tried both SomeError += "" and SomeError = std::string(Class->GetErrorMessage()) to explicitly make a copy but without altering the contents, but both failed (guess the compiler outsmarted me :/ ). Ideas?
-
I think it may be due to reference counting in std::string. If so, FreeLibrary might be killing the main version of the string before time.
I guess you could return a const pointer to a C type string in the function declaration...then in the implementation, if you have a std::string return std::string::c_str().
Havent tested whether this is the case though
-
I found out that self assignment solved it:
Code:
std::string SomeError = Class->GetErrorMessage();
SomeError = SomeError;
But I hate having the user be dependent on doing this... :/
I'd prefer not using old char pointers as strings. And even if I did, it would still point to the memory inside the std::string thanks to c_str() so I'm not sure it would solve the problem...
-
>>And even if I did, it would still point to the memory inside the std::string thanks to c_str() so I'm not sure it would solve the problem...
Yeah but I assumed if it were assigning a char ptr to a std::string it would do a deep copy and avoid the reference count. As I said...this is just me postulating as I dont have a chance to test it or even confirm that it's a point of reference counting.