c++ - 从 new 重载调用构造函数和直接调用构造函数有什么区别?

标签 c++ qt operator-overloading constructor-overloading

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

  1. void* operator new(std::size_t size, QString name, int id) 要调用的重载
  2. Foo(QString name, int 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 因为 id 没有在默认构造函数中初始化)。

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

参见 SO对于类似的问题。

关于c++ - 从 new 重载调用构造函数和直接调用构造函数有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35804798/

相关文章:

C++ 动态分配 header

c++ - Qt Custom Widget外观在设置样式表后没有改变

python - PyQt4中如何检测cellwidget用户点击QTableWidget的行号和列号?

c++ - 有没有办法将所有赋值运算符(+=、*= 等)转发为隐式使用重写的直接赋值运算符 (=)?

c++ - OpenCV 鱼眼校准削减了太多的结果图像

c++ - 在给定的输出中找到最大值

c++ - std::set 用作静态模板化成员变量

c++ - 可以在QML中的 map 上绘制带有孔的MapPolygon吗?

c++ - 重载智能指针指向的成员函数

c++ - 如何重载运算符 += 以添加两个类对象