Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uniform initializer used in default argument to const reference

Is this legal c++0x syntax?

class A
{
public:
    void some_function( const std::set<std::string> &options = {} );
    // note that this is legal, which binds the const reference to a temporary:
    void some_function( const std::set<std::string> &options = std::set<std::string>() );
}

Because if so, I just found a bug in GCC 4.6.

The error I get is:

error: expected primary-expression before '{' token

which is ... logical ... if it was illegal.

UPDATE: As @Kerrek has illustrated, this bleeds into plain C++03, with aggregates and the old brace initialization syntax for them. Why is this not possible? Is it forbidden in the Standard? Or are compilers at fault? Or is this an oversight? I don't see any serious problems in allowing this as an alternative to explicitely calling the constructor.

like image 893
rubenvb Avatar asked Jul 07 '11 19:07

rubenvb


People also ask

What is uniform initialization?

Uniform initialization is a feature in C++ 11 that allows the usage of a consistent syntax to initialize variables and objects ranging from primitive type to aggregates. In other words, it introduces brace-initialization that uses braces ({}) to enclose initializer values.

CAN default arguments be const C++?

A default argument is a value in the function declaration automatically assigned by the compiler if the calling function does not pass any value to that argument. The values passed in the default arguments are not constant. These values can be overwritten if the value is passed to the function.

Does default constructor initialize members?

Default constructors are one of the special member functions. If no constructors are declared in a class, the compiler provides an implicit inline default constructor. If you rely on an implicit default constructor, be sure to initialize members in the class definition, as shown in the previous example.

Is default constructor mandatory in c++?

The compiler-defined default constructor is required to do certain initialization of class internals. It will not touch the data members or plain old data types (aggregates like an array, structures, etc…). However, the compiler generates code for the default constructor based on the situation.


1 Answers

It is valid in C++11, but it was a very late addition to the working paper that Bjarne put through. So it's not surprising that GCC doesn't support brace default arguments yet.

like image 130
Johannes Schaub - litb Avatar answered Oct 01 '22 03:10

Johannes Schaub - litb