我想知道的是代碼是否多次調用析構函數,以及它是否正確以這種方式編碼。看起來像創建的對象在加載到矢量中之前超出了範圍,但對象並未死亡,而是停留在向量中,並在程序完成時再次破壞。繼承人的輸出:C++矢量對象和過度調用析構函數?
object::constructor:
before push_back
object::destructor:
object::constructor:
before push_back
object::destructor:
object::destructor:
object::call(): begin
0
object::call(): end
object::call(): begin
1
object::call(): end
object::destructor:
object::destructor:
Process returned 0 (0x0) execution time : 0.313 s
Press any key to continue.
這是main.cpp中
#include <vector>
#include <iostream>
#include "object.h"
int main()
{
int max = 2;
std::vector <object> OBJECTS;
for(int index = 0; index < max; index++)
{
object OBJECT(index);
std::cout<<"before push_back"<<std::endl;
OBJECTS.push_back(OBJECT);
}
for(int index = 0; index < max; index++)
OBJECTS[index].call();
return 0;
}
,這是object.h
#ifndef OBJECT_H
#define OBJECT_H
#include <iostream>
class object
{
private:
int value;
public:
object(){}
object(int value)
{
std::cout<<"object::constructor: "<<std::endl;
this->value = value;
}
~object()
{
std::cout<<"object::destructor: "<<std::endl;
}
void call()
{
std::cout<<"object::call(): begin"<<std::endl;
std::cout<<value<<std::endl;
std::cout<<"object::call(): end"<<std::endl;
}
};
#endif
這是從回答Chowlett下面的代碼,只需在案件的情況下。
#include <iostream>
#include <vector>
class object
{
private:
int value;
public:
object(){}
object(int value)
{
std::cout<<"object::constructor: "<< value << std::endl;
this->value = value;
}
object(const object& o)
{
std::cout<<"object::copy-constructor: " << o.value << std::endl;
this->value = o.value + 10;
}
~object()
{
std::cout<<"object::destructor: "<< value << std::endl;
}
void call()
{
std::cout<<"object::call(): begin"<<std::endl;
std::cout<<value<<std::endl;
std::cout<<"object::call(): end"<<std::endl;
}
};
int main()
{
int max = 3;
std::vector <object> OBJECTS;
for(int index = 0; index < max; index++)
{
object OBJECT(index);
std::cout<<"before push_back: capacity="<< OBJECTS.capacity() << std::endl;
OBJECTS.push_back(OBJECT);
std::cout<<"after push_back: capacity="<< OBJECTS.capacity() << std::endl;
}
for(int index = 0; index < max; index++)
OBJECTS[index].call();
return 0;
}
[STL Vector調用未分配對象的析構函數嗎?](http://stackoverflow.com/questions/7534504/is-stl-vector-calling-a-destructor-of-a-未分配的對象) – Praetorian 2013-03-07 17:28:31