MFC Question, Returning a local CString.

Status
Not open for further replies.
Instinct allways told me this was illegal, but now I think maybe I'm wrong:

code:<HR>
Code:
CString CSQLWrapper::CleanString(const CString &strSQL)
{
	CString strReturn(strSQL);
	strReturn.Replace("'", "''");
	return strReturn;
}

As you can see, A CString object is created local to the function, manipulated, and then returned by value.

With most objects this would be completely illegal because the object would be distroyed at the end of the function, and you'd be returning basically a block of freed memory to the caller. Often the program still works because the freed memory still contains the contents you expect.

However, CString is reference counted. So does it handle this case correctly? MSDN Implies that it does, however the example they show has them returning a member variable, which is a completely different case (and how I've always done CString returns).

Please don't guess at whether it is legal. I'm looking for peice of mind.
 

rsprawls

Smack-Fu Master, in training
75
Originally posted by grey:
I don't see what makes it illegal. You create a local copy of the string, manipulate it, and then return a copy of the manipulated string.

Now, if your function had been CString& CleanString(CString&), you'd have a problem, because you'd be returning a reference to something that no longer exists.

It's not illegal, but it is not guaranteed that the return value will be the expect result, since the stack space has been free'd.
 

rsprawls

Smack-Fu Master, in training
75
Originally posted by Jebediah:
Instinct allways told me this was illegal, but now I think maybe I'm wrong:

Quote: "CString CSQLWrapper::CleanString(const CString &strSQL)
{
CString strReturn(strSQL);
strReturn.Replace("'", "''");
return strReturn;
}"

With most objects this would be completely illegal because the object would be distroyed at the end of the function, and you'd be returning basically a block of freed memory to the caller. Often the program still works because the freed memory still contains the contents you expect.

However, CString is reference counted. So does it handle this case correctly? MSDN Implies that it does, however the example they show has them returning a member variable, which is a completely different case (and how I've always done CString returns).

Don't count on it working right. The space allocated to local variables is free'd when the function returns. If you're getting correct results now, it simply means the space hasn't been overwritten yet. I would recommend using a value-reslt variable or allocating via new and returning the reference to the space.
 

DrPizza

Well-known member
93,870
It doesn't return a local, it returns a copy of a local, and that copy is made on the stack of the caller, not the callee.

Consider (VS.NET beta 2, hence <span style="font-family: monospace;">__asm</span> not <span style="font-family: monospace;">asm</span>):


Code:
class C
{
public:
	C() {}
	C(const C& rhs) { cout << "copy c-tor" << endl; cout << "original: " << (size_t)&rhs << " copy: " << (size_t)this << endl; }
};<P>C foo(void)
{
	size_t stackPointer;
	__asm mov stackPointer, esp
	cout << "esp: " << stackPointer << endl;
	C retVal;
	return retVal;
}<P>int main(int argc, char* argv[])
{
	size_t stackPointer;
	__asm mov stackPointer, esp
	cout << "esp: " << stackPointer << endl;
	foo();
}

The stack pointer points at the bottom of the stack, and moves downward in the memory space with each function call (that is, the "top" of the stack is at the lowest stack memory address).

The output is something like this:
Code:
esp: 1244796
esp: 1244556
copy c-tor
original: 1244767 copy: 1244815

Between 1244796 and 1244556 is the stack of <span style="font-family: monospace;">foo()</span>. But our copy is at 1244815, which is on the stack of the caller.

If your compiler was sufficiently liberal, you could do something like this:
<span style="font-family: monospace;">(C*)this = (C*)&rhs;</span>
in your copy c-tor, which would create the copy on the stack of the callee, which would be a Bad Thing. Whilst MSVC++ permits this, it generates a warning (about casting an l-value).
 
f your compiler was sufficiently liberal, you could do something like this:
(C*)this = (C*)&rhs;
in your copy c-tor, which would create the copy on the stack of the callee, which would be a Bad Thing. Whilst MSVC++ permits this, it generates a warning (about casting an l-value).
How would this produce any result? I thought "this" was a local "variable". Changing its value shouldn't have any effect outside the method (although I have seen code that plays with it).
 

DrPizza

Well-known member
93,870
Hm, perhaps. I'm not sure. I never really thought of it like that (as a pseudo-local variable), but I suppose it is. I'm not sure what would happen if you then tried to run a method, though (the <span style="font-family: monospace;">this</span> pointer gets passed on ECX, with "thiscall" function calls -- if it is literally the <span style="font-family: monospace;">this</span> pointer, then it's gonna be fucked up).
 

Catfish

Ars Tribunus Angusticlavius
9,954
It doesn't return a local, it returns a copy of a local, and that copy is made on the stack of the caller, not the callee
Now I'm confused. Does 'return' always create a copy of the value on the stack of the caller, for any variable type?

I assume that 'return 3x4' drops 12 immediately onto the caller stack, rather than creating it locally & copying it. How about if it uses variables local to the callee?
 
Ok...

Well it sounds like returning CString by value is safe.

As I said, for most objects it would not be, becuase the destructor of the local variable would be called at the end of the function.

But CString is pretty smart, and reference counts the actual string data inside so that it is not destroyed until all the copies of CString are destroyed.

If returning CString truely creates a copy on the stack of the caller, then the data in the CString should be safe, and I think it will even clean itself up if the return value is not assigned to anything. It will also do it without making multiple copies of the actual string data.

But if anyone thinks I'm wrong let me know.

BTW, it's not a case of whether I should play it better safe than sorry, because I just found a lot of this in someone else's code.
 
I'm not sure what would happen if you then tried to run a method, though (the this pointer gets passed on ECX, with "thiscall" function calls -- if it is literally the this pointer, then it's gonna be fucked up).
Well, I think I've seen it around here in production code (yeah we *do* have really ugly code). It must have been compiler dependant though as IIRC upgrading the compiler resulted in "not an l-value". The code would pass a reference to this and potentially null it.
 
Originally posted by Catfish:
Now I'm confused. Does 'return' always create a copy of the value on the stack of the caller, for any variable type?

I assume that 'return 3x4' drops 12 immediately onto the caller stack, rather than creating it locally & copying it. How about if it uses variables local to the callee?
<span style="font-family: monospace;">return</span> creates the copy directly on the stack of the caller. If you create a new object, it doesn't create a local version and copy it, it creates it right where it needs to be.

This is a thing to consider when optimizing code, as a means of eliminating temporaries -- that is, if you had a function like this:
Code:
int addOne(int val) // first copy (from caller's stack)
{
    int retVal(val); // second copy
    retVal = retVal + 1; // assignment which may or may not be efficient
    return retVal; // third copy (to caller's stack)
}
It'd be better as:
Code:
int addOne(const int& val) // no copy
{
    return (val + 1); // created directly on caller's stack
}

<hr>

Well it sounds like returning CString by value is safe.
Returning anything by value is always safe. The only issue is if the copy c-tor is <span style="font-family: monospace;">private</span>, in which case a copy can't be made, or if the copy c-tor is deliberately broken.

As I said, for most objects it would not be, becuase the destructor of the local variable would be called at the end of the function.
No!

A copy of the local is made on the stack of the calling application prior to the destruction of the callee's locals.

It is always safe, unless the copy c-tor is <span style="font-family: monospace;">private</span> or the copy c-tor is deliberately broken.
 
Status
Not open for further replies.