我的课是这样的
class variable
{
public:
variable(int _type=0) : type(_type), value(NULL), on_pop(NULL)
{
}
virtual ~variable()
{
if (type)
{
std::cout << "Variable Deleted" <<std::endl;
on_pop(*this);
value=NULL;
}
}
int type;
void* value;
typedef void(*func1)(variable&);
func1 on_pop;
}然后我将实例推入std::vector中,如下所示:
stack.push_back(variable(0));我期望调用变量的析构函数,但if不会进入,直到为type赋值,因为我期望我提供的构造函数将在实例被复制到向量中时被调用。但出于某种原因,情况并非如此。
调用stack.push_back后,析构函数(副本的?)并且type有一些随机值,就像从未调用过构造函数一样。
我似乎想不出我做错了什么。请帮帮我!^_^
编辑:
好的,这里有一个自包含的例子来说明我的意思:
#include <iostream>
#include <vector>
class variable
{
public:
variable(int _type=0) : type(_type), value(NULL), on_pop(NULL)
{
}
~variable()
{
if (type)
{
std::cout << "Variable Deleted" <<std::endl;
on_pop(*this);
value=NULL;
}
}
int type;
void* value;
typedef void(*func1)(variable&);
func1 on_pop;
};
static void pop_int(variable& var)
{
delete (int*)var.value;
}
static void push_int(variable& var)
{
var.type = 1;
var.value = new int;
var.on_pop = &pop_int;
}
typedef void(*func1)(variable&);
func1 push = &push_int;
int main()
{
std::vector<variable> stack;
stack.push_back(variable(0));
push(stack[stack.size()-1]);
stack.push_back(variable(0));
push(stack[stack.size()-1]);
stack.push_back(variable(0));
push(stack[stack.size()-1]);
return 0;
}上面的程序输出如下:
Variable Deleted
Variable Deleted
Variable Deleted
Variable Deleted
Variable Deleted
Variable Deleted
Process returned 0 (0x0) execution time : 0.602 s
Press any key to continue.发布于 2012-05-26 21:00:40
好的。我已经阅读了更多关于不同容器的内部特性,显然,我在这里试图完成的工作是std::deque。
https://stackoverflow.com/questions/10764974
复制相似问题