Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor was called when assignment operator not implemented

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;
}
like image 547
Harsh Patel Avatar asked Mar 06 '23 03:03

Harsh Patel


1 Answers

What is compiler doing behind the curtain in this case?

Given s="Hello World";,

  1. A temporary String is constructed (implicitly converted) from "Hello World" via String::String(const char*).

  2. 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.

like image 110
songyuanyao Avatar answered Apr 27 '23 01:04

songyuanyao