make_shared是否为每个成员变量执行默认的初始化(零初始化) [英] Does make_shared do a default initialization (zero-init) for each member variable

查看:314
本文介绍了make_shared是否为每个成员变量执行默认的初始化(零初始化)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

采用普通的旧数据类型和对象作为成员的普通结构(或类)。注意,没有定义默认构造函数。

Take an ordinary struct (or class) with Plain Old Data types and objects as members. Note that there is no default constructor defined.

struct Foo
{
    int x;
    int y;
    double z;
    string str;
};

现在,如果我在堆栈上声明实例f并尝试打印其内容:

Now if I declare an instance f on the stack and attempt to print its contents:

{
    Foo f;
    std::cout << f.x << " " << f.y << " " << f.z << f.str << std::endl;
}

结果是为x,y和z打印的垃圾数据。并且该字符串默认初始化为空。 符合预期。

The result is garbage data printed for x, y, and z. And the string is default initialized to be empty. As expected.

如果我使用以下方式创建 shared_ptr< Foo> 的实例 make_shared 并打印:

If I create an instance of a shared_ptr<Foo> using make_shared and print:

{
    shared_ptr<Foo> spFoo = make_shared<Foo>();
    cout << spFoo->x << " " << spFoo->y << " " << spFoo->z << spFoo->str << endl;
}

然后,x,y和z均 0 。这样,在构造对象实例之后, shared_ptr 似乎在每个成员上执行默认初始化(零初始化)。至少我在Visual Studio的编译器中观察到了这一点。

Then, x, y, and z are all 0. Which makes it appear that shared_ptr performs a default initialization (zero init) on each member after the object instance is constructed. At least that's what I observe with Visual Studio's compiler.

这是C ++的标准吗?还是在实例化之后有必要使用显式构造函数或显式 = {} 语句来保证所有编译器的零初始化行为?

Is this standard for C++? Or would it be necessary to have an explicit constructor or explicit ={} statement after instantiation to guarantee zero-init behavior across all compilers?

推荐答案

如果看到例如 std :: make_shared 参考您会看到

If you see e.g. this std::make_shared reference you will see that


该对象的构造就像由表达式 :: new(pv )T(std :: forward< Args>(args)...),其中 pv 是内部 void * 指向适合保存类型为 T 的对象的存储的指针。

The object is constructed as if by the expression ::new (pv) T(std::forward<Args>(args)...), where pv is an internal void* pointer to storage suitable to hold an object of type T.

这意味着 std :: make_shared< Foo>()基本上是 new Foo()。也就是说,它 值初始化 归零非类成员变量。

That means std::make_shared<Foo>() basically does new Foo(). That is, it value initializes the structure which leads to the zeroing of the non-class member variables.

这篇关于make_shared是否为每个成员变量执行默认的初始化(零初始化)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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