std :: allocator construct / destroy vs. placement new / p->〜T() [英] std::allocator construct/destroy vs. placement new/p->~T()

查看:180
本文介绍了std :: allocator construct / destroy vs. placement new / p->〜T()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的项目,我从头开始编写一些STL容器(我有我的理由)。因为我正在模仿STL的功能和接口,所以我尽最大努力保持政策如果它有一个标准结构的相同名称,它将尽可能符合标准。



所以,当然我的容器把分配器作为一个模板参数,这是非常好的,因为它允许一些自定义分配方案。对我的问题。



std :: allocator 接口将内存分配与对象构造分离。同样,它将释放与销毁分离开来。这是有道理的,因为你从哪里得到的内存或多或少与在c ++中正确构造一个对象无关。



所以有两个构造/释放函数,默认实现(从一本书直接提取):

  void construct(pointer p,const T& val){new )T(val); } 
void destroy(pointer p){p->〜T(); }

你可以看到construct只是调用placement new和destroy只是调用析构函数。



有没有任何理由使用这些只是使用placement new和destructor语法?可以正确分配器以另一种方式实现这些?或者,我保证所有符合标准的分配器实现都会有这样的结构/销毁方法实现?



更重要的是,我总是可以使用 std :: uninitialized_copy std :: uninitialized_fill 来构造我的容器的元素? / p>

感谢。

解决方案

构造/破坏或任何其他需要做的副作用。



当然,实际的构造必须通过调用placement new和析构函数来实现,但它不会在规则手册中,没有别的必须发生在构造/销毁函数


For a project of mine, I am writing some STL containers from scratch (I have my reasons). Since I am mimicking the functionality and interfaces of the STL so closely I am doing my best to keep with the policy "if it has the same name as a standard construct, it will conform to the standard as much as possible."

So, of course my containers take allocators as a template parameter, which is very nice as it allows for some custom allocation schemes. On to my question.

The std::allocator interface separates memory allocation from object construction. Likewise it separates deallocation from destruction. This makes sense since where you get memory from is more or less irrelevant to properly constructing an object in c++.

So there are two construction/deallocation functions which look like this for the default implementation (lifted straight from a book):

void construct(pointer p, const T& val)    { new(p) T(val); }
void destroy(pointer p)                    { p->~T(); }

as you can see construct simply calls placement new and destroy simply calls the destructor.

Is there any reason to use these over just using placement new and destructor syntax? can a "correct" allocator implement these in another way? Or am I guaranteed that all allocator implementations which conform to the standard will have there construct/destroy methods implemented in this way?

More to the point, is it safe to say that I can always use the std::uninitialized_copy and std::uninitialized_fill for constructing the elements of my containers?

Thanks.

解决方案

The allocator could add logging statements before and after construction/destruction, or any other side effects it cared to do.

Of course the actual construction has to occur by calling placement new and the destructor, but it doesn't say in the rulebook that nothing else must happen in the construct/destroy functions

这篇关于std :: allocator construct / destroy vs. placement new / p->〜T()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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