so i ran along this question in a past test from my uni, and i noticed something strange that i couldn't find an explanation to.
the question is: what would the line cout << s2;
in main
would print?
I followed to flow execution in the VS2019 debugger and when the line MyString s2 = s1;
was performed it called
operator const char* ()const { return str; }
and I couldn't figure why it would go there. After that the ctor would be called on s2.
I understand why the copy ctor wouldn't be called on this instance because it is explicit
and in order to invoke it the line should have been MyString s2(s1);
for example.
main:
int main()
{
MyString s1;
cout << s1;
MyString s2 = s1;
cout << s2;
return 1;
}
The code:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class MyString
{
class MyChar
{
MyString * pStr;
int index;
public:
MyChar(MyString * p, int i) : pStr(p), index(i) {}
const MyChar & operator=(char c) {
pStr->set(index, c); // call copy-on-write
return *this;
}
operator char()const { return pStr->str[index]; }
};
friend class MyChar;
char* str;
int* ref_counter;
void attach(const MyString & s) {
ref_counter = s.ref_counter;
str = s.str;
++(*ref_counter);
}
void detach() {
if (--(*ref_counter) == 0) {
delete[]str;
delete ref_counter;
}
}
void set(int index, char c) {
// this is the copy-on-write
MyString temp(str);
detach();
attach(temp);
str[index] = c;
}
public:
MyString(const char* s = "") : ref_counter(new int(1))
{
str = new char[strlen(s) + 1];
strcpy(str, s);
}
explicit MyString(const MyString& s) { attach(s); }
~MyString() { detach(); }
const MyString & operator=(const MyString & s)
{detach(); attach(s); return *this; }
operator const char* ()const { return str; } //operation in question
MyChar operator[](int index) {
return MyChar(this, index);
}
char operator[](int index)const {
return str[index];
}
friend ostream & operator<<
(ostream & out, const MyString & s) {
return out << s.str << ", ref count = "
<< *s.ref_counter << endl;
}
};
Hope someone can help me understand this transition
question from:
https://stackoverflow.com/questions/65885762/operator-const-char-and-explicit-copy-ctor 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…