STL容器中复制语义背后的基本原理。 [英] Rationale behind copy semantics in STL containers.

查看:69
本文介绍了STL容器中复制语义背后的基本原理。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对专家来说只是一个简单的理论问题。


制作STL容器的理由是遵循复制

语义而不是参考语义。引用几乎总是

使事情变得更容易而没有太多的开销。那么为什么不参考?


谢谢

/ P

Just a simple theoritical question to the experts.

What was the rationale behind making STL containers follow copy
semantics rather than reference semantics. References almost always
make things easier without much of overhead. Then why not reference ?

Thanks
/P

推荐答案

dragoncoder写道:
dragoncoder wrote:

对专家来说只是一个简单的理论问题。


制作STL的理由是什么容器遵循复制

语义而不是引用语义。引用几乎总是

使事情变得更容易而没有太多的开销。那么为什么不参考?


谢谢

/ P
Just a simple theoritical question to the experts.

What was the rationale behind making STL containers follow copy
semantics rather than reference semantics. References almost always
make things easier without much of overhead. Then why not reference ?

Thanks
/P



因为有一个有效的参考你必须在其他地方有一个对象

,因此你必须知道该对象的生命周期。这个

留下了悬挂引用和内存泄漏的可能性。

STL容器拥有自己的对象并在

容器后自行清理破坏,基本上解决了这两个问题。


如果你真的想要相当于存储的引用,你可以制作一个

的指针容器 - 很可能

引擎盖下的引用是什么无论如何。

Because to have a valid reference you must somewhere else have an object
and you must therefore be aware of the lifetime of that object. This
leaves open the possibilities of dangling references and memory leaks.
STL containers own their objects and clean up after themselves when the
container is destructed, essentially solving both of these problems.

If you really want the equivalent of a stored reference, you can make a
container of pointers-- likely that''s what a reference is "under the
hood" anyway.




Mark P kirjoitti:

Mark P kirjoitti:

如果你真的想要相当于存储的引用,你可以在

引擎盖下制作一个

指针容器 - 很可能就是引用的内容。无论如何。
If you really want the equivalent of a stored reference, you can make a
container of pointers-- likely that''s what a reference is "under the
hood" anyway.



或者更确切地说,是一个内存地址。 ;)

Or more precisely, a memory address. ;)




dragoncoder写道:

dragoncoder wrote:

只是一个向专家提出简单的理论问题。


使STL容器遵循复制

语义而非参考语义的原因是什么。引用几乎总是

使事情变得更容易而没有太多的开销。那么为什么不参考?
Just a simple theoritical question to the experts.

What was the rationale behind making STL containers follow copy
semantics rather than reference semantics. References almost always
make things easier without much of overhead. Then why not reference ?



因为C和C ++总是基于价值而且总是允许

你使用指针以防你真的想要参考语义。 (我相信这些措辞来自Java - 因此它在C ++

上下文中会产生误导)。并且引用确实有很多开销:这就是为什么

简单对象例如整数是基于价值的语言,例如

Java(需要拳击才能作为真实对象)。


/ Peter


这篇关于STL容器中复制语义背后的基本原理。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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