放置新的推迟到不同的构造函数 [英] placement new to defer to a different constructor

查看:184
本文介绍了放置新的推迟到不同的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是安全吗?我没有在我的实际实现中使用任何虚拟函数,但我很想相信即使我是,它仍然是安全的。

Is this safe? I'm not using any virtual functions in my actual implementation, but I'm tempted to believe that even if I was, it would still be safe.

class Foo
{
    Foo()
    {
        // initialize things
    }

    Foo( int )
    {
         new ( this ) Foo();
    }
}


推荐答案

当你输入 Foo(int)构造函数的打开的大括号时,所有类成员都调用了它们的构造函数。如果您随后强制调用另一个具有placement new的构造函数,那么您将覆盖类的当前状态。这基本上意味着所有成员的构造函数都被调用了两次 - 如果在它的构造函数中 new ,你泄漏了这些内容,你真的会搞错了! 您正在有效构建两个对象,并且第一个对象的成员的析构函数从不调用,因为第二个对象覆盖第一个对象的内存。

By the time you enter the open curly brace of the Foo(int) constructor, all class members have had their constructor called. If you then force a call to another constructor with placement new, you're overwriting the current state of the class. This basically means all members have their constructors called twice - if something does new in its constructor, you leak that content, and you will really, really mess things up! You're effectively constructing two objects, and the destructors for the members of the first object are never called, since the second object overwrites the memory of the first object.

换句话说,它 BAD !不要这样做!

In other words it's BAD! Don't do it!!

最常见的解决方法是使用某种初始化函数,并从两个构造函数调用它。这不会让你初始化const成员和其他必须在初始化列表中。

The most common workaround is to use some kind of initialisation function, and call that from both constructors. This won't let you initialize const members and others that must be in the initializer list, though.

这篇关于放置新的推迟到不同的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆