在方法中调用的将值传递给变量的析构函数

问题描述 投票:-1回答:2

我正在创建伪std :: vector。我希望能够声明变量Matrix B,然后将其赋值,并由另一个Matrix变量传递。Matrix有构造函数,分配备忘录

Vect(int size, char name) : name(name), size(size), store(new int[size]){}

和在生命周期结束时将其删除的析构函数

~Vect(){
  std::cout << "memo located: " << name << std::endl;
  delete[] store;
}

不幸的是,用于返回值的方法使用称为析构函数的方法将其返回

  Vect operator- (){
    Vect b(size,'C');
    for (int i = 0; i < size; i++){
      b.store[i] = -store[i];
    }
    return b; // <- here it calls destructor!!!
  }

我尝试这样做:

  Vect m2;
  Vect m1 = Vect(10, 'A'); 
  m2 = -m1;

我收到此错误:

memo located: C
-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, 
memo located: A
memo located: C
a.out(46158,0x109e71dc0) malloc: *** error for object 0x7f9162401850: pointer being freed was not allocated
a.out(46158,0x109e71dc0) malloc: *** set a breakpoint in malloc_error_break to debug
Abort trap: 6

如何保存已保存的功能?我的代码:

#include <iostream> 

class Vect { 
  int *store; 
  int size = 0; 
  char name;

  public:
  Vect operator- (){
    Vect b(size,'C');
    for (int i = 0; i < size; i++){
      b.store[i] = -store[i];
    }
    return b;
  }

  int *getPointer(){
    return store;
  }
  int getSize(){
    return size;
  }

  bool set(int i, int v){
    if (i >= size)
      return false;
    store[i] = v;
    return true;
  }

  Vect(){}
  Vect(int size, char name) : name(name), size(size), store(new int[size]){}
  ~Vect(){
    std::cout << "memo located: " << name << std::endl;
    delete[] store;
    }
}; 


int main(int argc, char **argv){ 
  Vect m2;
  Vect m1 = Vect(10, 'A'); 

  int i = 0;
  while(m1.set(i++, i));

  m2 = -m1;
  int size = m2.getSize(), *ptr = m2.getPointer();
  for (int i = 0; i < size; i++){
    std::cout << ptr[i] << ", ";
  }
  std::cout << std::endl;
  return 0; 
} 
c++ oop constructor destructor
2个回答
1
投票

我相信您想实现“复制和交换习惯”。您需要将b(临时对象)中的数据交换到您的对象中,然后临时销毁该临时对象。

演示:https://wandbox.org/permlink/BMccSpz03cpGuG6S


0
投票

我想做的是不可能实现的。 operator-应该反转原始对象,或者我应该实现operator=并修改operator-

© www.soinside.com 2019 - 2024. All rights reserved.