This may be a really silly question but it’s something I’ve been struggling with. After changing the LPWSTR in a method it appears to only be changing for that specific method and reverting back immediately after. I know global variables are evil but this is not my choice because it would require changing quite a bit of code. Here’s an example of what I’m doing:
Test.h
static LPWSTR globalStr = L"This shouldn't be here.";
// The ...s are irrelevant code.
class Test {
public:
...
void changeGlobalStr();
void testMethod();
...
...
};
Test.cpp
#include "Test.h"
Test::changeGlobalStr() {
string testString("This should be here.");
// I manipulate testString over the next few lines so a variable is necessary.
...
BSTR bConversion = _com_util::ConvertStringToBSTR(testString.c_str());
globalStr = bConversion
// This prints out the correct output.
wcout << "globalStr in changeGlobalStr(): " << globalStr;
}
SecondTest.cpp
#include "Test.h"
Test::testMethod() {
changeGlobalStr();
// Get correct output from the print inside the method.
wcout << "globalStr in testMethod(): " << globalStr;
// Now incorrect output is printed.
}
testMethod() ends up printing out “This shouldn’t be here” instead of “This should be here”. I’m not entirely sure what I’m doing wrong but I feel like it’s something elementary and I’m just very rusty in my C++.
Yes, indeed, the text in the LPWSTR is correct: “This shouldn’t be here.” The problem is that globalStr isn’t global. It’s defined as
staticin the header, so each source file gets its own copy of globalStr. Changing it in one source file doesn’t change it in any of the others.To fix it, give it an
externdeclaration in the header and define it in one source file:// Test.h:
extern LPWSTR globalStr;
// Test.cpp:
LPWSTR globalStr = L”This shouldn’t be here.”