我一直在这个页面上查找一些C++的东西.
有关复制赋值运算符的以下示例:
Example5& operator= (const Example5& x) {
delete ptr; // delete currently pointed string
ptr = new string (x.content()); // allocate space for new string, and copy
return *this;
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,这一点对我来说很清楚,但文章指出:
或者甚至更好,因为它的字符串成员不是常量,它可以重用相同的字符串对象:
Example5& operator= (const Example5& x) {
*ptr = x.content();
return *this;
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么会这样.这不是我们想要实现的第一个例子吗?:复制分配内容.为什么"重用同一个字符串对象"?
该页面说明:
[...]隐式版本执行浅拷贝,适用于许多类,但不适用于具有指向其存储的对象的指针的类,如Example5中的情况.在这种情况下,不仅类会产生两次删除指向对象的风险,而且分配通过在分配之前不删除对象指向的对象来创建内存泄漏.
让我们再看一遍代码:
#include <iostream>
#include <string>
using namespace std;
class Example5 {
string* ptr;
public:
Example5 (const string& str) : ptr(new string(str)) {}
~Example5 () {delete ptr;}
// copy constructor:
Example5 (const Example5& x) : ptr(new string(x.content())) {}
// access content:
const string& content() const {return *ptr;}
};
Run Code Online (Sandbox Code Playgroud)
因此,复制赋值运算符的隐式版本将等效于
Example5& operator= (const Example5& x) {
ptr = x.ptr; // previous value of ptr is lost -> memory leak
return *this;
}
Run Code Online (Sandbox Code Playgroud)
这会产生内存泄漏,因为它不会释放元素指针this.ptr.建议的版本deallocate ptr然后为它分配新的内存.取消分配和分配会产生额外的成本和额外的指令,因此第二个代码
Example5& operator= (const Example5& x) {
*ptr = x.content();
return *this;
}
Run Code Online (Sandbox Code Playgroud)
重用(this-> ptr)相同(已分配)的内存区域来存储副本*x.ptr.
注意,由于x.content()返回的字符串的副本x,*ptr = x.content();会调用copy assignment operator的*ptr这硫杂的情况下是一个字符串.
| 归档时间: |
|
| 查看次数: |
545 次 |
| 最近记录: |