[英]print an array after deep copying in c++ classes
我想實現以下行為:
我寫的代碼如下:
#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 = new float;
只分配一個float
。 這意味着在這個循環中:
for(int i=0 ; i<_size; ++i){
cout << *(ptr+i)
一旦i
大於 0,就取消引用無效內存,這是未定義的行為。 這導致程序可以做任何事情,包括產生您看到的“垃圾”輸出。
如果要分配數組,則需要執行以下操作:
ptr = new float[_size];
要刪除它,您需要執行以下操作:
delete [] ptr;
請注意,即使您如上所示正確分配了內存,您實際上也沒有從參數中復制數據。 只是設置指針會做一個淺拷貝,這不是你想要的。
你可以做一個這樣的深拷貝:
std::copy(d.ptr, d.ptr + _size, ptr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.