【发布时间】:2015-12-14 05:39:10
【问题描述】:
我正在尝试使此代码正常工作,但对象不断被破坏... 我发现它与被复制到向量的对象有关,但找不到任何方法来阻止它......
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Obje
{
private:
static int instances;
int id;
public:
static int getInstances();
void getId();
virtual void myClass();
Obje(int auxId);
~Obje();
};
int Obje::instances = 0;
int Obje::getInstances()
{
return instances;
}
Obje::Obje(int auxId)
{
this->id = auxId;
cout << "Obje Created." << endl;
Obje::instances++;
}
Obje::~Obje()
{
cout << "Obje Destroyed." << endl;
Obje::instances--;
}
void Obje::myClass()
{
cout << "Obje." << endl;
}
void Obje::getId()
{
cout << this->id << endl;
}
int main()
{
vector <Obje> list;
Obje *a = new Obje(59565);
list.push_back(*a);
Obje *b = new Obje(15485);
list.push_back(*b);
for(vector<Obje>::iterator it = list.begin(); it != list.end(); ++it)
{
it->getId();
}
return 0;
}
它生成这个输出:
Obje Created.
Obje Created.
Obje Destroyed.
59565
15485
Obje Destroyed.
Obje Destroyed.
我认为T(const T& new); 是什么意思?
【问题讨论】:
-
T(const T&obj);是 复制构造函数。查一下。 -
首先,您需要阅读this comment,然后阅读this question,以了解如何在C++中使用内存。这是 C++ 而不是 Java。
-
这里不需要任何
new表达式。他们只会为您制造 nemory 泄漏。 C++ 不是 Java。 -
不使用
new我有 5 次调用析构函数...我如何实现这个复制构造函数? -
当然析构函数最终必须被执行!怎么了?
标签: c++