Code:
#include <iostream>
#include <cstring>
class MyString
{
public:
MyString() {
std::cout << "1";
}
explicit MyString(const char *str) {
std::cout << "2";
}
};
int main()
{
MyString str1 = MyString("abcde");
MyString str2("abcde");
MyString str3 = "abcde";
return 0;
}
str1
and str2
are created just fine, printing out 2
. But when I run it with str3
I get the following error message:
Compilation failed due to following error(s).main.cpp: In function ‘int main()’:
main.cpp:19:19: error: conversion from ‘const char [6]’ to non-scalar type ‘MyString’ requested
19 | MyString str3 = "abcde";
Aren’t all 3 lines supposed to call the second constructor, because of rvo? Or is it because I’m using a non-rvo compiler? I tried it both on CMake and gcc and both have the same error message.
I tried creating an operator=
and still got the same error, so it clearly isn’t from rvo:
#include <iostream>
#include <cstring>
class MyString
{
public:
MyString() {
std::cout << "1";
}
explicit MyString(const char *str) {
std::cout << "2";
}
MyString& operator=(const char *str) {
std::cout << "3";
return *this;
}
};
int main()
{
MyString str1 = MyString("abcde");
MyString str2("abcde");
MyString str3 = "abcde";
return 0;
}
I searched around for quite a bit, but couldn’t find an answer