Yes, your concerns are legitimate. You need to use specifically designed function like SecureZeroMemory() to prevent optimizations from modifying your code behavior.
Don’t forget that the string class should have been specifically designed for handling passwords. For example, if the class reallocates the buffer to hold a longer string it has to erase the buffer before retunring it to the memory allocator. I’m not sure, but it’s likely std::string
doesn’t do that (at least by default). Using an unsuitable string handling class makes all your concerns worthless – you’ll have the password copied all over the program memory befoe you even know.