C++ 在将值传递给变量的方法中调用析构函数
我正在创建伪std::vector。我希望能够声明变量C++ 在将值传递给变量的方法中调用析构函数,c++,oop,constructor,destructor,C++,Oop,Constructor,Destructor,我正在创建伪std::vector。我希望能够声明变量矩阵B,然后给它赋值,并通过另一个矩阵变量传递。 矩阵具有分配备忘录的构造函数 Vect(int size, char name) : name(name), size(size), store(new int[size]){} 以及在var生命周期结束时删除它的析构函数 ~Vect(){ std::cout << "memo located: " << name << std::endl; de
矩阵B
,然后给它赋值,并通过另一个矩阵
变量传递。
矩阵
具有分配备忘录的构造函数
Vect(int size, char name) : name(name), size(size), store(new int[size]){}
以及在var生命周期结束时删除它的析构函数
~Vect(){
std::cout << "memo located: " << name << std::endl;
delete[] store;
}
我得到了这个错误:
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
如何在保存功能的情况下绕过它?
我的代码:
#包括
类向量{
int*商店;
int size=0;
字符名;
公众:
向量运算符-(){
向量b(大小,'C');
对于(int i=0;i=大小)
返回false;
存储[i]=v;
返回true;
}
Vect(){}
Vect(int size,char name):名称(name),大小(size),存储(newint[size]){}
~Vect(){
std::cout我相信您想要实现“复制和交换习惯用法”。您需要将b
(临时对象)中的数据交换到您的对象中,然后安全地销毁临时对象
演示:我试图做的是不可能实现的。要么操作符-
应该反转原始对象,要么我应该实现操作符=
并在(m1.set(I++,I))时修改操作符-;
可能会导致在表达式中对同一标量进行多个修改,但没有任何中间序列点(直到C++11),这些修改是未排序的(从C++11开始)。1,2:不,它没有回答我的问题Q 3:我知道,我不是在问…(1,2)是的,m2=-m1;
调用内置赋值运算符,该运算符复制原始指针store
,并使m1
和m2
都认为它们拥有内存,从而导致双重删除。另外Vect m1=Vect(10,'A'))
调用复制构造函数-同样的问题只在这里m1
现在持有一个指向已经删除的内存的指针。或者在内存缓冲区内部使用std::vector
,或者std::unique\u ptr
@Krasnay Danil是的,这正好回答了你的问题。你读过它们的链接吗?理解3的规则吗(5从C++11开始)您将知道出了什么问题。@Krasnay Danil没有详细介绍。如果您编写的类中默认的复制/移动不够,您基本上有三个选择:要么实现所需的复制和移动操作,要么删除它们以防止它们被使用,要么尝试更改类的实现,以便可以使用默认值。如果无法以这种方式实现您的类,并且您希望复制/移动,那么实现5的规则是没有办法的。我建议让操作符更改对象和复制构造函数,以获取对象并复制它。因此m1=-m2
将按预期工作.
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;
}