从新重载调用构造函数和直接调用构造函数有什么区别?
What's the difference between call constructor from new overload and directly?
考虑下面的代码,当我调用new(name, 10) Foo()
时,我希望按顺序发生以下情况:
-
void* operator new(std::size_t size, QString name, int id)
要调用的重载 -
从上面的重载调用
Foo(QString name, int id)
构造函数此时,为我的类分配了足够的内存,因此我可以安全地执行和设置:姓名(名称), ID(ID)
-
调用
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
相关文章:
- 在c++中使用向量时,如何调用构造函数和析构函数
- C++:考虑但不调用构造函数的特殊性
- 对象实例化调用构造函数的次数太多
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- C ++:通过大括号调用构造函数?
- 不能调用构造函数
- 赋值 boost::intrusive_ptr 而不调用构造函数?
- 在模板化类的构造函数中调用构造函数
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- 静态 std::map instatiation 在类的方法中调用构造函数吗?
- 有没有一种简单的方法可以在对象向量上调用构造函数?
- 我不明白在这个例子中什么时候调用构造函数
- 调用c++构造函数的不同方法
- 调用构造函数与将内联常量定义为默认参数
- 如何通过 Rust FFI 调用C++构造函数?
- "new"运算符是否总是调用构造函数?
- 无法调用构造函数
- 使用 "()" 调用构造函数不同于"{}"
- 确定是调用构造函数还是强制转换运算符的因素