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;
}
explicit.if (capacity == 1) delete start;is a very bad idea. Even if younew[]ed a one-long array, you must delete it withdelete[]. Or better, use anstd::unique_ptr<char[]>.