【问题标题】:What's the difference between call constructor from new overload and directly?从新重载调用构造函数和直接调用构造函数有什么区别?
【发布时间】:2016-03-04 19:45:11
【问题描述】:

考虑到下面的代码,当我调用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;

【问题讨论】:

  • 应该使用new operator中的额外参数来选择内存管理策略。这在实现将管理自己的内存的自定义容器时很有用。此值不应用于初始化对象。
  • @MarekR:传递给 new 运算符的参数与我传递构造函数来创建对象的参数完全相同,所以我只传递一次

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


【解决方案1】:

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

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

请参阅SO 了解类似问题。

【讨论】:

  • 您说的是 C++ 生成的还是我的默认构造函数?我不明白name 值是如何被覆盖的,而id 却没有。两者都设置在构造函数Foo(QString, int)
  • Foo *f = new (name, 10) Foo; 调用你的构造函数Foo(); Foo *f = new (name, 10) Foo(name, 10); 将调用 Foo(QString, int) 构造函数。
  • 我试图从void* operator new(std::size_t size, QString name, int id)重载调用Foo(QString, int)构造函数来初始化成员。在对Foo() 的调用中,应该已经设置了该值,因此它什么也不做。
猜你喜欢
  • 2013-05-08
  • 1970-01-01
  • 1970-01-01
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
  • 2011-10-23
  • 1970-01-01
  • 2019-08-30
相关资源
最近更新 更多