I'm a bit confused about how scopes should function in C++. Right now it seems to be the case that inside my else statement, my finalStr is created and then promptly destroyed after it leaves the scope.

std::string finalStr;
char curLine[128];
if( BINARY_ASCII == 1 ) //ignore this case please :D
{
    cdata = convertBSTRToByteArray(data , numChars);
}
else
{
    bstrInputString = ( LPCWSTR ) data;

    std::strcpy(curLine, bstrInputString.operator char *());
    std::string finalStr(curLine);

    cout << "data is: " << finalStr.data() << "\n"; //prints the right string
}

cout << "string is: " << finalStr.data() << "\n"; //prints nothing except "string is: "

How can I fix this? I believe I need that copy constructor in the else statement to copy over my array of chars. Is there a way around this? Thanks for reading..

有帮助吗?

解决方案

You have finalStr declared twice, one outside the if-else statement and one time inside. The one declared in the inner scope will hide the one in the outer scope, so what you have is a local variable that will be destroyed at the end of the enclosing brace.

However, std::string can be assigned to easily, so just use that:

finalStr = curLine;

其他提示

The very first line in your code snippet (std::string finalStr;) declares the finalStr variable.

Then, within the else part you're declaring another variable named finalStr which is local to that scope (the opening brace after the else to its matching closing brace). This variable now hides the first one, and references to finalStr within this scope, after the declaration, will refer to the local variable, not the finalStr declared in the enclosing scope.

To fix the problem, do not re-declare the variable, just assign finalStr a new value.

std::strcpy(curLine, bstrInputString.operator char *());
finalStr = curLine;
//     ^^^^^
// assign new value instead of creating another variable with the same name

std::string finalStr(curLine);

This line creates a NEW string, which just happens to have the same name as your string on the top of your code.

Change the line to this

finalStr = curLine

This copies curLine into the finalStr you have declared at the top.

It's just a matter of declaring the variable in the scope you need it. In fact, you were already doing this. Then, don't declare it again. Just assign it a value. When you declare it again, a completely new variable is created (just that with the same name). It is this second variable what is lost.

finalStr= curLine ;

It is said that the second variable is "hiding" or "shadowing" the first.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top