This program, when compiled with VC12 (in Visual Studio 2013 RTM)[1] leads to a crash (in all build configurations), when really it shouldn't:
#include <string>
void foo(std::string const& oops = {})
{
}
int main()
{
foo();
}
I know of two silent bad codegen bugs that might be related:
- https://connect.microsoft.com/VisualStudio/feedback/details/800364/initializer-list-calls-object-destructor-twice
- http://connect.microsoft.com/VisualStudio/feedback/details/800104/
Honestly I think these are different, though. Does anyone know
- whether there is an actively tracked bug on connect for this
- whether there is a workaround (or an explicit description of the situation that causes this bug, so we can look for it/avoid it in our code base)?
[1] Just create an empty project using the C++ Console Application 'wizard'. For simplicity, disable precompiled headers and leave all defaults: http://i.stack.imgur.com/rrrnV.png
An active issue was posted back in November. The sample code posted was:
The bug has been acknowledged by Microsoft.
There doesn't seem to be a work-around posted there. Edit Workarounds can easily be based on avoiding the list-initializer syntax:
Or just the old-fashioned (if you don't mind introducing overloads):
It looks like
Visual Studio
is just broken with respect to which constructor it calls when the default argument is an initializer list. This code:produces this result in
gcc
andclang
, see it live here:while
Visual Studio
produces this result:and for this code:
gcc
andclang
produce this result see it live here:while
Visual Studio
produces this error:Update
For a sanity check, I went back to the standard to make sure there wasn't some odd rule at the root of this difference or perhaps some restriction that makes this code ill-formed. As far as I can tell this code is not ill-formed. Section
8.3.5
grammar specifically allows this:It does not seem like section
8.5
Initializers or8.3.6
Default arguments add any restrictions but this defect report 994. braced-init-list as a default argument and working paper Wording for brace-initializers as default arguments make it clear that it was intended and outline the changes made to the standard to allow it and looking at the deltas there are no obvious restrictions.