I thought that when doing this:
String s1 = "hello";
there are 2 operations happening (e.g., as said here): (1) constructing a temporary object with the string literal "hello"
, and then (2) copy-constructing s1
with the temporary object.
However, when running the following code, the only printing I get is from String's constructor, and not from its copy constructor. Why?
static char *AllocAndCpy(const char *src_);
class String
{
public:
String(const char *string_="");
String(const String &other_);
private:
char *m_str;
};
String::String(const char *string_): m_str(AllocAndCpy(string_))
{
std::cout << "constructor" << std::endl;
}
String::String(const String &other_):m_str(other_.m_str)
{
std::cout << "copy constructor" << std::endl;
}
static char *AllocAndCpy(const char *src_)
{
size_t src_length = strlen(src_)+1;
char *dest_ = new char[src_length];
return (static_cast<char *>(memcpy(dest_, src_, src_length)));
}
int main()
{
String s1 = "hello";
return 0;
}