在列表中插入会更改值c++

Inserting in a list changes values c++

本文关键字:c++ 列表 插入      更新时间:2023-10-16

我想创建多个"体素"对象并将它们放在列表中。但如果我这样做,由体素存储的两个值就会改变。这是类的定义:

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

这是复制构造函数:

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){}

用这个代码我插入它们:

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

如果查看变量,在创建单个体素对象后,seg_fac和sf_counter的值是正确的。但如果我插入它们,并在列表中查找它们,它们就会变成8744512或-236461096。所以我的问题是,这是从哪里来的?

感谢您的帮助,并提前表示感谢。

在摆弄了constructersdestructorsoperator=之后,我发现我只是忘记添加

int sf_counter;
bool subdiv;
int seg_fac;

到我的copy-constructor。所以工作的copy-constructor看起来像:

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