Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

explicit constructor taking `std::string` gets `char*` and works fine

Tags:

c++

c++11

Marking StringBuilder constructor as explicit I think I couldn't pass in char* but it seems I can as it compiles just fine.

class StringBuilder {
public:
//    StringBuilder(const char *);
    explicit StringBuilder(std::string s) {}
};

int main() {

    StringBuilder s1("hello");
    StringBuilder s2(std::string("hello"));

}

http://cpp.sh/6uomq

like image 395
lukas.pukenis Avatar asked Dec 21 '15 09:12

lukas.pukenis


1 Answers

basic_string constructor taking a character pointer is not explicit:

basic_string( const CharT* s,  Allocator& alloc = Allocator() );

This means that providing a char pointer to function which takes string will implicitly create a string and pass it to the function.

You are making StringBuilder explicit, which means that it is not possible to implicitly convert string to StringBuilder, i.e. if you pass a string to a function which takes StringBuilder as argument, it will fail to compile.

EDIT: as noted by @Revolver_Ocelot, you can declare the offending constructor (StringBuilder(const char*)) as deleted to prevent it from being used. If you can't use C++11, you can just declare the same constructor as private and omit the definition (implementation):

class StringBuilder 
{
  public:
    explicit StringBuilder(const std::string& s) {}    

  // for C++11 use this:
    StringBuilder(const char*) = delete;

  // otherwise use this:
  private:
    StringBuilder(const char*); // no implementation
};
like image 55
Zdeslav Vojkovic Avatar answered Oct 10 '22 02:10

Zdeslav Vojkovic