【发布时间】:2016-03-04 19:45:11
【问题描述】:
考虑到下面的代码,当我调用new(name, 10) Foo() 时,我预计会按顺序发生以下情况:
-
void* operator new(std::size_t size, QString name, int id)重载被调用 -
Foo(QString name, int id)从上面重载调用的构造函数 此时,已为我的班级分配了足够的内存,因此我可以安全地进行设置:名称(名称),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;
【问题讨论】:
-
应该使用new operator中的额外参数来选择内存管理策略。这在实现将管理自己的内存的自定义容器时很有用。此值不应用于初始化对象。
-
@MarekR:传递给 new 运算符的参数与我传递构造函数来创建对象的参数完全相同,所以我只传递一次
标签: c++ qt operator-overloading constructor-overloading