6

The following code compiles fine on g++ (various versions) but fails on clang++-3.4 with libc++ on my system:

#include <map>
#include <string>

std::map<std::string, std::string> f() {
    return {};
}

int main() {
    auto m = f();
}

clang marks the following problem:

x.cpp:6:12: error: chosen constructor is explicit in copy-initialization
    return {};
           ^~
/usr/local/Cellar/llvm34/3.4.2/lib/llvm-3.4/bin/../include/c++/v1/map:838:14: note: constructor declared here
    explicit map(const key_compare& __comp = key_compare())
             ^

Indeed, the include file declares the constructor as explicit. But it’s not marked as such in my C++11 draft standard. Is this a bug in clang++/libc++? I was unable to find a relevant bug report.

4
  • 1
    It looks like it is explicit after all (at least, until C++14): en.cppreference.com/w/cpp/container/map/map Jul 11, 2017 at 9:07
  • In the current working draft n4659 it is also marked explicit. Jul 11, 2017 at 9:09
  • @KonradRudolph In your example and the error message, you are not invoking the copy constructor, the problem comes before that - when you are trying to default construct a std::map. Jul 11, 2017 at 9:15
  • @Thomas I’m blind. Jul 11, 2017 at 9:15

1 Answer 1

9

There is no empty constructor before C++14. Default construction for std::map<Key, Value, Compare, Allocator> is marked explicit with 2 default parameters until C++14:

explicit map( const Compare& comp = Compare(), 
              const Allocator& alloc = Allocator() );

After C++14, we have a non-explicit empty default constructor which calls the explicit constructor from before (which now does not have a default Compare argument):

map() : map( Compare() ) {}
explicit map( const Compare& comp, 
              const Allocator& alloc = Allocator() );

So your example would only be valid after C++14.

Source: http://en.cppreference.com/w/cpp/container/map/map

5
  • Thanks, makes perfect sense. So g++ 4.8 (with -std=c++1) was wrong to accept it, correct? Jul 11, 2017 at 9:17
  • @KonradRudolph Yes, GCC should have rejected this when compiling with a C++11 compliant standard library. Jul 11, 2017 at 9:18
  • Fair enough, but isn't a constructor whose parameters are all defaulted technically the default constructor – assuming there is no "real" default c'tor?
    – Arne Vogel
    Jul 11, 2017 at 11:33
  • 1
    BTW, note how the comp parameter is no longer defaulted in C++14, probably to avoid ambiguity.
    – Arne Vogel
    Jul 11, 2017 at 11:35
  • "A default constructor for a class X is a constructor of class X for which each parameter that is not a function parameter pack has a default argument (including the case of a constructor with no parameters)."
    – T.C.
    Jul 11, 2017 at 21:04

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.