简体   繁体   English

在未实现赋值运算符时调用构造函数

[英]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. 我在Visual Studio 2015中练习'String'类实现(C ++)。我的类中有3个构造函数,而不是任何赋值运算符。

String();
String(char _c);
String(const char* _pc);

In main() , i am deliberately using assignment operator to check behavior of the code. main() ,我故意使用赋值运算符来检查代码的行为。

To my surprise, it is not giving any error and uses the constructor String(const char* _pc) to assign value to the object. 令我惊讶的是,它没有给出任何错误,并使用构造函数String(const char* _pc)为对象赋值。 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"; 给定s="Hello World"; ,

  1. A temporary String is constructed (implicitly converted) from "Hello World" via String::String(const char*) . 通过String::String(const char*)"Hello World"构造(隐式转换)临时String

  2. s is assigned from the temporary via implicitly-declared move assignment operator ( String::operator=(String&&) ). s是从临时通过隐式声明的移动赋值运算符String::operator=(String&&)赋值的

BTW you might mark String::String(const char*) explicit to prohibit the implicit conversion which happened at step#1. 顺便说一下,您可以将String::String(const char*) explicit标记为禁止在步骤#1中发生的隐式转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM