【发布时间】:2020-09-17 21:17:12
【问题描述】:
正如下面的代码,复制赋值运算符必须检查输入对象是否指向自身。我想知道为什么复制构造函数不需要做同样的检查。
我是 C++ 新手。如果能在这个问题上提供一些帮助,我将不胜感激。
class rule_of_three
{
char* cstring; // raw pointer used as a handle to a dynamically-allocated memory block
void init(const char* s)
{
std::size_t n = std::strlen(s) + 1;
cstring = new char[n];
std::memcpy(cstring, s, n); // populate
}
public:
rule_of_three(const char* s = "") { init(s); }
~rule_of_three()
{
delete[] cstring; // deallocate
}
rule_of_three(const rule_of_three& other) // copy constructor
{
init(other.cstring);
}
rule_of_three& operator=(const rule_of_three& other) // copy assignment
{
if(this != &other) {
delete[] cstring; // deallocate
init(other.cstring);
}
return *this;
}
};
【问题讨论】:
-
因为复制构造的时候,构造出来的对象不可能是被复制的那个……可以测试,但是这种情况永远不会发生。
-
@IgorR。但是存储对未初始化对象的引用是允许的,不是吗?我认为是。
-
@HolyBlackCat 如何获得对未初始化对象的引用?
-
@user207421 很简单,将它传递给它自己的复制ctor。 :P
MyClass foo(foo);. -
@IgorR。我们可以称其为“未初始化的存储”,但重点仍然存在。
标签: c++ c++11 constructor copy-constructor assignment-operator