+3  A: 

The * 2 is because RegSetValueEx wants to know the number of bytes to write und each char (wchar_t) in a wstring is two bytes wide. So the resulting byte-array has twice the size!

Dario
It's more portable to use "sizeof _TCHAR" insetad of 2. :-D
Chris Jester-Young
So it would be better to write wNewValue.size()*sizeof(wchar_t) to make it clear what's going on.
Mark Ruzon
+7  A: 
void function(const std::string& newValue)
{
    HKEY keyHandle;
    if(RegOpenKeyEx(HKEY_CLASSES_ROOT, TEXT("some key"),0,KEY_ALL_ACCESS,&keyHandle) == ERROR_SUCCESS)
    {

        if (RegSetValueExA(keyHandle, "some value", NULL, REG_SZ, (const BYTE*)newValue.c_str(), newValue.size() + 1)==ERROR_SUCCESS)
        {
                //do something
        }
        RegCloseKey(keyHandle);
    }
}

I removed the part where you convert your string to a wstring, instead you'll be using the ANSI version of RegSetValueEx explicitly.

quote from RegSetValueEx remarks in MSDN:

If dwType is the REG_SZ, REG_MULTI_SZ, or REG_EXPAND_SZ type and the ANSI version of this function is used (either by explicitly calling RegSetValueExA or by not defining UNICODE before including the Windows.h file), the data pointed to by the lpData parameter must be an ANSI character string. The string is converted to Unicode before it is stored in the registry.

Also note that the cbData parameter should include the size of the null termination aswell.

Idan K
If you're explicitly using the ANSI version, you shouldn't use the TEXT() macro, which will expand to L"foo" if UNICODE is defined.
Adam Rosenfield
copy paste back firing! removed, thanks.
Idan K
So as long as I don't use any non-ANSI characters I'm just fine using the ANSI versions of winapi functions? (that seems logical, but I didn't think of that)
Emile Vrijdags
the Win32API functions that expect text are divided to ANSI (ends with A in the function name) and Unicode (ends with W), most of them anyway. so you could use std::string with the A's and std::wstring with the W's.
Idan K
@ejac: your example would not have worked if your input has characters outside of (probably) ASCII anyway since you were doing a bitwise expansion with `wNewValue.assign(newValue.begin(), newValue.end())`. Remember that wNewValue is a UNICODE character sequence so the bitwise assignment will only work if all of the character points in newValue are valid UNICODE code points. In other words, newValue contains ONLY ISO-8859-1 characters.
D.Shawley