考虑下面的代码,当我调用 new(name, 10) Foo()
时,我希望按顺序发生以下情况:
void* operator new(std::size_t size, QString name, int id)
要调用的重载Foo(QString name, int id)
从上面重载调用的构造函数 此时,我的类分配了足够的内存,所以我可以安全地做和设置:名字(名字),身份证(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;
最佳答案
Foo *f = new (name, 10) Foo;
使用重载的 ǹew
分配内存运算符,然后使用默认构造的 Foo
初始化内存(它只覆盖 name
但不覆盖 id
因为 id
没有在默认构造函数中初始化)。
您可以通过放置例如qDebug() << __PRETTY_FUNCTION__;
在 Foo 的构造函数中。
参见 SO对于类似的问题。
关于c++ - 从 new 重载调用构造函数和直接调用构造函数有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35804798/