Search code examples
c++listpush-back

Inserting in a list changes values c++


I want to create multiple "voxel"-objects and put them in a list. But if I do so two of the values, that are stored by voxel, change. Here is the class definition:

class Voxelization{

private:
int sf_counter;
bool subdiv;
int seg_fac;
int* labels;
Pixel<int>* centers;
int n_seeds;
float* pixels;
float* depth;
int width;
int height;
int iterations;
float r1;
float r2;
int env_size;
bool move_centers;
typename pcl::PointCloud<PointT>::ConstPtr& cloud;
typename NormalCloudT::ConstPtr normal_cloud;
}

And this is the copy constructor:

Voxelization::Voxelization(const Voxelization& voxel):labels(voxel.labels), centers(voxel.centers),n_seeds(voxel.n_seeds),pixels(voxel.pixels),depth(voxel.depth),width(voxel.width),height(voxel.height),iterations(voxel.iterations),r1(voxel.r1),r2(voxel.r2),env_size(voxel.env_size),move_centers(voxel.move_centers),cloud(voxel.cloud){}

And with this code I'm inserting them:

  int seg_fac=100;
  int sf_counter=0;
  std::list<Voxelization> voxels
  for(sf_counter; sf_counter<seg_fac;sf_counter++){
      Voxelization voxel(input_cloud_ptr,seg_fac,sf_counter);
      voxels.push_back(voxel);
  }

If I look at the variables, after I create the single voxel-objects, the values for seg_fac and sf_counter are right. But if I then insert them, and look them up in the list they change to something like 8744512 or -236461096. So my question is, where does this come from?

Any help is appreciated, and thanks in advance.


Solution

  • After fiddling around with my constructers, destructors and the operator= I found out that I simply forgot to add

    int sf_counter;
    bool subdiv;
    int seg_fac;
    

    to my copy-constructor. So the working copy-constructor looks like:

    Voxelization::Voxelization(const Voxelization& voxel):sf_counter(voxel.sf_counter),subdiv(voxel.subdiv),seg_fac(voxel.seg_fac),labels(new int[voxel.width*voxel.height]), centers(voxel.centers),n_seeds(voxel.n_seeds),pixels(new float[voxel.width*voxel.height*3]),depth(new float[voxel.width*voxel.height]),width(voxel.width),height(voxel.height),iterations(voxel.iterations),r1(voxel.r1),r2(voxel.r2),env_size(voxel.env_size),move_centers(voxel.move_centers),cloud(voxel.cloud),normal_cloud(voxel.normal_cloud){
    std::copy(voxel.labels, voxel.labels + voxel.width*voxel.height, labels);
    std::copy(voxel.pixels, voxel.pixels + voxel.width*voxel.height*3, pixels);
    std::copy(voxel.depth, voxel.depth + voxel.width*voxel.height, depth);
    std::copy(voxel.centers, voxel.centers + voxel.width*voxel.height, centers);
    }