全局范围LPWSTR在更改后恢复

Tay*_*lon 2 c++ windows scope global-variables visual-studio-2008

这可能是一个非常愚蠢的问题,但这是我一直在努力的事情.在方法中更改LPWSTR后,它似乎只是针对该特定方法进行更改并在之后立即恢复.我知道全局变量是邪恶的,但这不是我的选择,因为它需要更改相当多的代码.这是我正在做的一个例子:

Test.h

static LPWSTR globalStr = L"This shouldn't be here.";

// The ...s are irrelevant code.
class Test {
    public:
        ...
        void changeGlobalStr();
        void testMethod();
        ...
    ...
};
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

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.
}
Run Code Online (Sandbox Code Playgroud)

testMethod()最终打印出"这不应该在这里"而不是"这应该在这里".我不完全确定我做错了什么,但我觉得这是一些基本的东西,而且我的C++非常生疏.

Pet*_*ker 5

是的,确实,LPWSTR中的文字是正确的:"这不应该在这里." 问题是globalStr不是全局的.它static在头文件中定义,因此每个源文件都有自己的globalStr副本.在一个源文件中更改它不会在其他任何文件中更改它.

要修复它,extern在标题中给它一个声明并在一个源文件中定义它:

// Test.h:

extern LPWSTR globalStr;

// Test.cpp:

LPWSTR globalStr = L"这不应该在这里."