我尝试通过谷歌和搜索来回答我的问题,但是我找不到任何有效的解释,因此我在这里发布我的问题。以下是我的示例代码和输出:
#include <iostream>
#include "vector"
using namespace std;
typedef struct Node{
int data;
Node(){
data = 0;
std::cout << "Node created. " << this <<'\n';
}
~Node(){
data = 0;
std::cout << "Node destroyed. " << this <<'\n';
}
} Node;
int main() {
std::vector<Node> vec;
for(int i = 0; i < 2 ; i++)
vec.push_back( *(new Node));
return 0;
}
输出:
Node created. 0x9e0da10
Node created. 0x9e0da30
Node destroyed. 0x9e0da20
Node destroyed. 0x9e0da40
Node destroyed. 0x9e0da44
为什么有一个额外的销毁,以及创建的对象和销毁的对象不同?
vec.push_back(Node());
。 - PaulMcKenzievec.push_back( *(new Node));
这段代码也让我感到身体疼痛。 - underscore_dclass noisy
,并在需要添加此仪器的地方继承它。 - JDługosz