Explicit constructor accepting `std :: string` gets` char * `and works fine

Noting the constructor StringBuilderas explicit, I think I couldn't go in char*, but it seems like I can, because 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

+4
source share
1 answer

basic_stringConstructor with a character pointer not explicit:

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

This means that providing a char pointer to a function that accepts stringimplicitly creates a string and passes it to the function.

StringBuilder , , string StringBuilder, , string , StringBuilder , .

EDIT: @Revolver_Ocelot, (StringBuilder(const char*)) , . ++ 11, , private, ():

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
};
+10

Source: https://habr.com/ru/post/1621085/


All Articles