C++ 库研究笔记——拷贝构造函数的一个错误范例
来源:互联网 发布:慢摇吧软件 编辑:程序博客网 时间:2024/04/29 12:45
之前记录的有:
C++库研究笔记——赋值操作符operator=的正确重载方式(三个准则)
我原来的拷贝构造函数是这样写的:
explicit array1d(Index size=0,T val=T()) :size_(size),data_(0) { log_info("construct 1"); if(size==0) return; allocate(); // allocate memory for(int i=0; i<size_; i++){ data_[i]=val; } }
// 这样写的本意是:为了能够使用 std::vector<T> v_other; array1d<T> v(v_other); template<class ArrayType> array1d(const ArrayType& other) { log_info("arrayType"); size_= other.size(); allocate(); // copy value for(int i=0; i<size_; i++){ data_[i]=other[i]; } }
std::vector<real> v(3,9.0); array1d<real> b(v); b.print();
确实没有问题
但是:
array1d<float, long> dl(9l); dl[3]=4; dl.print("dl"); // array1d<float, long> dl2(dl); dl2.print("dl2");
编译没有问题,运行时会出现,double free memory
*** glibc detected *** ./main: double free or corruption (fasttop): 0x0000000001b85010 ***
通过追踪发现:
上面的代码根本没有调用
template<class ArrayType> array1d(const ArrayType& other) { log_info("arrayType"); size_= other.size(); allocate(); // copy value for(int i=0; i<size_; i++){ data_[i]=other[i]; } }而是,直接原始的拷贝,这样就会拷贝一个相同的数据指针位置,然后在相同的位置释放两次内存
解决办法:(追加如下代码)
array1d(const array1d & other) { log_info("array1d&"); size_= other.size(); allocate(); // copy value for(int i=0; i<size_; i++){ data_[i]=other[i]; } }
- C++ 库研究笔记——拷贝构造函数的一个错误范例
- 一个C++拷贝构造函数的例子
- 关于c++默认的构造函数、析构函数、拷贝构造函数、move函数
- 【C/C++】C++库研究笔记——函数名的宏定义
- c++之拷贝构造函数的研究
- C++——拷贝构造函数
- 【C++】基础知识—构造函数与拷贝构造函数
- C++ 库研究笔记——通过inline避免hpp 的mutiple definition 错误
- C++库研究笔记——#if #elif 的错误使用
- 拷贝构造函数的理解错误
- C++库研究笔记——函数名的宏定义
- C++构造 函数,析构函数,拷贝构造函数,赋值构造函数,一个内存错误例子!
- 【C++】拷贝构造函数
- C++:拷贝构造函数
- c++"拷贝构造函数
- C++: 拷贝构造函数
- 【C++】拷贝构造函数
- c++::拷贝构造函数
- 编程之美3.2 电话号码对应英语单词
- 字符串 移位包含
- 树的路径
- 文件指针位置操作
- 内存泄露及内存溢出
- C++ 库研究笔记——拷贝构造函数的一个错误范例
- 【7gyy】教你快速对异常错误进行更正
- Codeforces Round #131 (Div. 2) / 214A System of Equations(枚举&优化)
- 设备模型之一 kobject & kset
- Oracle名称含义列表
- 美女薄情馆7.0.0破解VIP
- Linux2.6内核 -- 结构的初始化
- Java动态编译
- 设备模型之二 总线设备驱动