【发布时间】:2021-01-23 18:02:51
【问题描述】:
我想实现以下行为:
- DataSequence 类有一个指针,指向主函数中的一个数组。
- 在初始化类 DataSequence 的对象时打印数组
- 创建同一对象的深层副本(通过复制构造函数)并在对象形成时打印它。
我写的代码如下:
#include<bits/stdc++.h>
using namespace std;
class DataSequence{
float *ptr;
int _size;
public:
DataSequence(float input[] , int size){
_size = size;
ptr = new float; ptr = input;
//print the array
cout << "Main constructor" << endl;
for(int i=0 ; i<_size; ++i){
cout << *(ptr+i) << " ";
// ++ptr;
}
}
//copy constructor
DataSequence(DataSequence &d){
_size = d._size;
ptr = new float; *ptr = *(d.ptr);
//print the array
cout << "copy constrructor" << endl;
for(int i=0 ; i<_size ; ++i){
cout << *(ptr+i) <<" ";
// ++ptr;
}
}
};
int32_t main(){
int size=4;
float input[size];
int bins;
input[0] = 3.4;
input[1] = 1.3;
input[2] = 2.51;
input[3] = 3.24;
DataSequence d(input , size);
cout << endl;
DataSequence d1 = d;
return 0;
}
输出如下
Main constructor
3.4 1.3 2.51 3.24
copy constrructor
3.4 2.42451e-038 -2.61739e-019 3.20687e-041
我无法弄清楚为什么我会从复制构造函数中得到垃圾,有人可以帮忙吗?
【问题讨论】:
-
这段代码应该在什么时候发生“深度复制”?
-
*ptr = *(d.ptr);不会对数组进行深拷贝。它只是复制第一个元素。ptr = input;不会进行深拷贝,也不会进行浅拷贝,并导致您在此行之前在ptr = new float;中分配的单个浮点数的内存泄漏。 -
这一行:“ptr = new float;”分配一个浮点数,下面的“ptr = input;”覆盖ptr,内存泄漏。请查看指针。
-
另外,样板警告
#include <bits/stdc++.h>是一个非常危险的习惯(请参阅stackoverflow.com/questions/31816095/… )并且当您编写float input[size];时您使用的是非标准编译器扩展以及您可能真正想要的是float* input = new float[size];。 -
复制构造函数也应该正确地具有签名
DataSequence(const DataSequence &d)
标签: c++ arrays oop pointers constructor