简体   繁体   English

在 C++ 类中深度复制后打印数组

[英]print an array after deep copying in c++ classes

I want to achieve the following behaviour:我想实现以下行为:

  1. The class DataSequence has a pointer that points to an array in the main function.类 DataSequence 有一个指向 main 函数中的数组的指针。
  2. print the array when an object in initialised of the class DataSequence当初始化类 DataSequence 的对象时打印数组
  3. create a deep-copy of the same object (via a copy constructor) and print it when the object is formed.创建相同对象的深层副本(通过复制构造函数)并在对象形成时打印它。

The code I have written is as follows:我写的代码如下:

#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;
}

The output is as follows输出如下

Main constructor
3.4 1.3 2.51 3.24
copy constrructor
3.4 2.42451e-038 -2.61739e-019 3.20687e-041

I am unable to figure out why I am getting garbage from the copy constructor, can someone help.我无法弄清楚为什么我从复制构造函数中获取垃圾,有人可以帮忙。

This statement:这个说法:

ptr = new float;

only allocates a single float .只分配一个float That means in this loop:这意味着在这个循环中:

for(int i=0 ; i<_size; ++i){
    cout << *(ptr+i)

as soon as i is greater than 0, you dereference invalid memory, which is undefined behavior.一旦i大于 0,就取消引用无效内存,这是未定义的行为。 This results in a program that can do anything, including producing the "garbage" output you see.这导致程序可以做任何事情,包括产生您看到的“垃圾”输出。

If you want to allocate an array, you need to do:如果要分配数组,则需要执行以下操作:

ptr = new float[_size];

and to delete it, you need to do:要删除它,您需要执行以下操作:

delete [] ptr;

Note that even if you allocate memory correctly as shown above, you are not actually copying the data from the argument.请注意,即使您如上所示正确分配了内存,您实际上也没有从参数中复制数据。 Just setting pointers would do a shallow copy which is not what you want.只是设置指针会做一个浅拷贝,这不是你想要的。

You can do a deep copy like this:你可以做一个这样的深拷贝:

std::copy(d.ptr, d.ptr + _size, ptr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM