Considering below code, when I call new(name, 10) Foo()
I expect the following to happen, in that order:
void* operator new(std::size_t size, QString name, int id)
overload to be calledFoo(QString name, int id)
constructor called from above overload at this time, enough memory is allocated to my class so I can safely do and set:name(name), id(id)
Call
Foo()
empty constructor and do nothing. Only here because must be implemented.
But I missing something. The member name value is empty. Would someone explain what and how to fix?
The code:
Note: QString is Qt's QString
type
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;
}
};
How I call this:
QString name = "BILL";
Foo *f = new(name, 10) Foo();
qDebug() << f->toString(); //output "name = , id = 10"
delete f;