OFC你可以从一个对象实例调用它,看到这样的代码:
#include <iostream>
class foo{
public :
int foo_var;
foo(){
std::cout<<"foo_var = "<<foo_var<<std::endl;
}
};
int main()
{
foo * f = new foo();
// set foo_var
f->foo_var = 10;
// call constructor by passing object instanse
foo * f1 = new(f) foo;
std::cout<<(f==f1)<<std::endl;
system("pause");
return 0;
}
第二输出为“foo_var = 10”,所以它是工作。第三个输出是“真”,然后(f == f1),这意味着构造函数不分配新的内存(操作符new,但我们传递了一个指针,所以他不会分配另一个) 那里你真的有用做法:
#include <iostream>
template <class t>
class smart_pointer{
t * p; // the real normal pointer
public :
smart_pointer()
{
p = (t*) malloc(sizeof(t)); // allocate memory
try{
new (p) t; // call the constructor
} catch (...) // if it throws any exception
{
free(p); // free p , dont use delete , because it will
// call the destroctor calling the destructor will cause
// freeing a not allocated memory that causes a crash
throw; // throw the exception what ever it was
}
}
~smart_pointer(){delete p;}
t operator = (t val) // assigment operator
{
*p = val;
return val;
}
operator t(){ // type casting operator , usually for std::cout
return *p;
}
};
int main()
{
smart_pointer<int> x;
x = 10;
std::cout<<x<<std::endl;
system("pause");
return 0;
}
建议改为 “有效的C++”, “更有效的C++”, “有效的现代C++” 的书籍
'C->〜CON();'可能是好的,但'删除c;'在下一行不是,因为它会试图再次调用同一个析构函数。 – Cubbi 2011-04-27 15:11:18
您正在通过_object pointer_调用析构函数。不是类指针。 – xtofl 2011-04-27 15:12:32
由于xtofl上面说过,您正在使用对象指针调用析构函数。但是如果你没有使用构造函数,你就没有指向构造函数的对象。 – Sam 2011-04-27 15:18:52