我想知道的是代码是否多次调用析构函数,以及以这种方式编码是否正确。似乎创建的对象在加载到向量中之前超出了范围,但对象并没有死亡,而是留在向量中,并在程序完成后再次破坏。这是输出:
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;
}