4

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;
}
2
  • 1
    Make your single argument constructors explicit. Commented May 23, 2018 at 8:45
  • 1
    if (capacity == 1) delete start; is a very bad idea. Even if you new[]ed a one-long array, you must delete it with delete[]. Or better, use an std::unique_ptr<char[]>. Commented Aug 30, 2019 at 12:12

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.