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
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
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With