考虑到下面的代码,当我打电话时,new(name, 10) Foo()
我希望按以下顺序发生以下情况:
void* operator new(std::size_t size, QString name, int id)
被调用的重载Foo(QString name, int id)
此时从上面重载调用的构造函数,为我的类分配了足够的内存,因此我可以安全地执行和设置:姓名(姓名),身份证(身份证)
调用
Foo()
空构造函数并且什么都不做。只有在这里因为必须执行。
但我错过了一些东西。成员名称值为空。有人会解释什么以及如何解决吗?
编码:
注意:QString 是 Qt 的QString
类型
class Foo
{
public:
QString name;
int id;
// The idea is return an already existing instance of a class with same values that
// we are going to construct here.
void* operator new(std::size_t size, QString name, int id)
{
Foo *f = getExistingInstance(name, id);
if(f != NULL)
return f;
/* call to constructor Foo(QString, int) is an alias for:
* Foo* *p = static_cast<Foo*>(operator new(size));
* p->name = name;
* p->id = id;
* return p;
* I don't think it's wrong on ambiguos in the below call to constructor, since it does use
* operator new(std::size_t size) and Foo(QString name, int id) "methods"
*/
return new Foo(name, id);
}
void* operator new(std::size_t size)
{
void *ptr = malloc(size);
assert(ptr);
return ptr;
}
Foo(QString name, int id)
: name(name),
id(id)
{
}
Foo()
{
}
~Foo()
{
}
QString toString()
{
return QString("name = %1, id = %2")
.arg(name)
.arg(id);
}
static Foo* getExistingInstance(QString name, int id)
{
/* not implemented yet */
return NULL;
}
};
我怎么称呼这个:
QString name = "BILL";
Foo *f = new(name, 10) Foo();
qDebug() << f->toString(); //output "name = , id = 10"
delete f;