从新重载调用构造函数和直接调用构造函数有什么区别?

What's the difference between call constructor from new overload and directly?

本文关键字:调用 构造函数 什么 区别 重载 新重载      更新时间:2023-10-16

考虑下面的代码,当我调用new(name, 10) Foo()时,我希望按顺序发生以下情况:

  1. void* operator new(std::size_t size, QString name, int id)要调用的重载
  2. 从上面的重载调用Foo(QString name, int id)构造函数此时,为我的类分配了足够的内存,因此我可以安全地执行和设置:

    姓名(名称), ID(ID)

  3. 调用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,因为 defualt 构造函数中未初始化id)。

您可以通过放置例如 qDebug() << __PRETTY_FUNCTION__;在 Foo 的构造函数中。

有关类似问题,请参阅 SO