Implicit construction of std :: string does not occur during copy initialization

I am trying to copy the initialization of my class CObjas follows in a function main():

#include <string>
#include <iostream>

class CObj
{
public:
   CObj(std::string const& str) : m_str(str) { std::cout << "constructor" << std::endl; }

   ~CObj() { std::cout << "destructor" << std::endl; }

private:
   std::string m_str;
};

int main()
{
    CObj obj = "hello";

    std::cout << "done" << std::endl;
}

However, the string CObj obj = "hello"does not compile, although it is std::stringimplicitly constructive from a char const*. In my opinion, this should work. Any reason why this is not so? If I do this, it works:

CObj obj = std::string("hello");
+4
source share
2 answers

A literal "Hello"is of the type const char[6]: to call your constructor, two transformations are required: one on std::stringand one on CObj.

But C ++ allows one user-defined conversion when performing an implicit conversion:

++ § 12.3/4 [class.conv]

.

[...]

1 ( ) .


:

CObj obj = std::string("hello");

:

CObj obj("hello");

, const char*:

CObj(const char* cstr) : m_str(cstr) { ... }

explicit, , - .

+4

(.. char[6]std::string std::stringCObj ).

:

int main()
{
    using namespace std::literals::string_literals; // this is necessary
                                                    // for the literal conversion

    CObj obj = "hello"s; // note the extra "s", (which constructs a std::string)

    std::cout << "done" << std::endl;
}
+2

All Articles