4

I wrote little wrapper for XML Lite library to use it in my MFC project. Can I use this code?

CString GetValue()
{
    const WCHAR* pwszValue = NULL;
    UINT cwchValue = 0;

    m_pReader->GetValue(&pwszValue, &cwchValue);

    return CString(pwszValue);
}

Or shoud I use CString& parameter in GetValue method signature?

3
  • 1
    Have you tested this? Well, the answer is yes, actually, but where do your doubts come from? Commented Jul 29, 2012 at 19:50
  • What is m_pReader? What error are you getting? Commented Jul 29, 2012 at 19:50
  • when it returns like this, will it call to the destructor of CString at the end of the method? Commented Dec 16, 2014 at 5:58

3 Answers 3

3

There's no need to return through a parameter, this should work.

If you're worried about efficiency, don't. Return value optimization will most likely occur in this case.

Sign up to request clarification or add additional context in comments.

2 Comments

Ehm, this is MSVC we're talking about here. Don't assume anything about optimisation. Test instead.
@MrLister: Yes, this is MSVC, there is no need to assume, it has been tested, it performs RVO.
1

If you're thinking about efficiency, then turn on optimization and measure. And consider whether the difference, if any, matters to you. It's almost sure that the compiler will do return value optimization (RVO) here.

But as a general rule, use the coding practice that gives you more clear code, i.e. in this case the function result, which gives more concise, robust and readable calling code.

That said, it looks like you're leaking memory for the pwszValue, and the Hungarian notation prefix is not exactly readable and reduces clarity, so the code needs a bit of reworking even when you do the sensible thing and use the function result value.

3 Comments

"it looks like you're leaking memory for the pwszValue" how come?
@Luchian: it could conceivably be that m_pReader->GetValue stores the address of a statically allocated string in pwszValue, but how likely is that.
Unfortunately it is extremely likely. GetValue(WCHAR**, UINT*) doesn't get you a value, but sets the parameter to point to a string that will be changed almost immediately afterwards.
0

CString& would be dead wrong, returns a reference to a temporary, your program would crash very quickly.

1 Comment

The OP means a CString& as a function parameter. That will work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.