为什么必须shared_ptr<>分别为控制块和管理对象分配? [英] Why must shared_ptr<> allocate for the control block and managed object separately?

查看:176
本文介绍了为什么必须shared_ptr<>分别为控制块和管理对象分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个链接的问题询问 make_shared<> 函数和 shared_ptr<> 构造函数是否不同。 / p>

使用make_shared时会发生什么



部分答案是 make_shared<> 通常会为对象和智能指针控制块在单个分配。 shared_ptr<> 构造函数使用两个分配。



cppreference 说明构造函数必须这样做,但没有给出任何原因。



为什么?是出于某种原因不可能吗? cd ::

解决方案

想想 std :: shared_ptr 构造函数:

  std :: shared_ptr< Foo>(new Foo 

首先, new Foo()评价; :: operator new Foo 对象分配内存,然后构建它。生成的指针作为参数传递给 std :: shared_ptr 构造函数。



看到问题了吗?已经执行了 Foo 分配!智能指针构造函数具有无选项,用于为同一分配中的控制块和对象分配空间,因为它不负责为对象分配内存。


另一方面,

std :: make_shared 负责两个分配,因此 可以在一个堆分配中分配空间,然后在该一个分配中对该对象和控制块进行placement-new-construct。


This linked question asked if the make_shared<> function and the shared_ptr<> constructor differ.

What happens when using make_shared

Part of the answer was that make_shared<> will usually allocate memory for both the pointed to object and smart pointer control block in a single allocation. The shared_ptr<> constructors use two allocations.

cppreference states that the constructors "must" do so but no reason is given.

Why is this? Is it for some reason impossible? Or is it forbidden by the standard for some other reason?

解决方案

Think about how the std::shared_ptr constructor works:

std::shared_ptr<Foo>(new Foo());

First the new Foo() expression is evaluated; ::operator new allocates memory for the Foo object and then constructs it. The resulting pointer is passed in as an argument to the std::shared_ptr constructor.

See the problem? The Foo allocation has already been performed! The smart pointer constructor has no option to allocate room for both the control block and the object in the same allocation, since it was not responsible for allocating memory for the object.

std::make_shared, on the other hand, is in charge of both allocations and so it is possible to allocate room for both in one heap allocation, and then placement-new-construct both the object and control block within that one allocation.

这篇关于为什么必须shared_ptr&lt;&gt;分别为控制块和管理对象分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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