2

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

  1. void* operator new(std::size_t size, QString name, int id)被调用的重载
  2. Foo(QString name, int 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;
4

1 回答 1

0

Foo *f = new (name, 10) Foo; 使用重载运算符分配内存ǹew,然后使用默认构造初始化内存Foo(仅覆盖name但不是id因为id未在默认构造函数中初始化)。

您可以通过将 egqDebug() << __PRETTY_FUNCTION__;放入 Foo 的构造函数中看到这一点。

有关类似问题,请参见SO 。

于 2016-03-04T20:43:17.360 回答