我有这样的课
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:: victor like this:
stack.push_back(variable(0));
我期望变量的毁灭器将被调用,但如果在指定输入某个值之前不输入,则在指定输入某个值之前,由于我期望当实例被复制到矢量中时,会调用我提供的构建器。但出于某种原因,它不会被调用。
在调用堆叠. push_ back back the devior (option?) 之后, 毁灭器( 复制件?) 被运行, 类型有随机值, 比如, 构建器从未被调用 。
我似乎无法理解我做错了什么 请救救我!
编辑:
Ok这里是一个自我包含的示例 来显示我的意思:
#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.