未实现赋值运算符时调用构造函数
Constructor was called when assignment operator not implemented
我在 Visual Studio 2015 年练习 'String' class 实现 (C++)。
我的 class 中有 3 个构造函数,但没有任何赋值运算符。
String();
String(char _c);
String(const char* _pc);
在 main()
中,我故意使用赋值运算符来检查代码的行为。
令我惊讶的是,它没有给出任何错误并使用构造函数 String(const char* _pc)
为对象赋值。
此外,在作用域的末尾,它调用了两次析构函数。
在这种情况下,编译器在幕后做了什么?为什么?
这是我的代码:
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?
给定 s="Hello World";
,
通过 String::String(const char*)
.
从 "Hello World"
构造(隐式转换)临时 String
s
通过 implicitly-declared move assignment operator (String::operator=(String&&)
) 从临时分配。
顺便说一句,您可以标记 String::String(const char*)
explicit
以禁止在第 1 步发生的隐式转换。
我在 Visual Studio 2015 年练习 'String' class 实现 (C++)。 我的 class 中有 3 个构造函数,但没有任何赋值运算符。
String();
String(char _c);
String(const char* _pc);
在 main()
中,我故意使用赋值运算符来检查代码的行为。
令我惊讶的是,它没有给出任何错误并使用构造函数 String(const char* _pc)
为对象赋值。
此外,在作用域的末尾,它调用了两次析构函数。
在这种情况下,编译器在幕后做了什么?为什么?
这是我的代码:
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?
给定 s="Hello World";
,
通过
String::String(const char*)
. 从 s
通过 implicitly-declared move assignment operator (String::operator=(String&&)
) 从临时分配。
"Hello World"
构造(隐式转换)临时 String
顺便说一句,您可以标记 String::String(const char*)
explicit
以禁止在第 1 步发生的隐式转换。