I am practicing 'String' class implementation (C++) in Visual Studio 2015. I have 3 constructors in my class and not any assignment operator.
String();
String(char _c);
String(const char* _pc);
In main()
, i am deliberately using assignment operator to check behavior of the code.
To my surprise, it is not giving any error and uses the constructor String(const char* _pc)
to assign value to the object.
Also, at the end of the scope, it is calling the destructor twice.
What is compiler doing behind the curtain in this case? and why?
Here is my code:
class String {
private:
int capacity;
char* start;
public:
//Constructors
String();
String(const char* _pc);
//Destructor
~String();
}
String::String() :start(nullptr), capacity(0) {}
String::String(const char* _pc) :capacity(1) {
const char* buffer = _pc;
while (*(buffer++))
capacity++;
int temp_capacity = capacity;
if (temp_capacity)
start = new char[temp_capacity];
while (temp_capacity--) {
start[temp_capacity] = *(--buffer);
}
}
String::~String() {
if (capacity == 1)
delete start;
if (capacity > 1)
delete[] start;
}
int main() {
String s;
s="Hello World";
return 0;
}
What is compiler doing behind the curtain in this case?
Given s="Hello World";
,
A temporary String
is constructed (implicitly converted) from "Hello World"
via String::String(const char*)
.
s
is assigned from the temporary via implicitly-declared move assignment operator (String::operator=(String&&)
).
BTW you might mark String::String(const char*)
explicit
to prohibit the implicit conversion which happened at step#1.
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