简体   繁体   English

即使在单线程程序中,共享指针是否在引用计数中使用原子操作

[英]Do shared pointers use atomic operations in reference counting even in a single threaded program

To be multi-thread safe, the std::shared_ptr uses atomic operations to perform reference counting.为了多线程安全,std::shared_ptr 使用原子操作来执行引用计数。 While this is good, I have the following questions:虽然这很好,但我有以下问题:

  1. If the program is a single-threaded one, is there a compiler smart enough to use plain (non-atomic) increment and decrement operations instead?如果程序是单线程程序,是否有足够聪明的编译器来使用普通(非原子)递增和递减操作?
  2. Following the above question, if the answer is no, is there a way to tell the compiler that he program is single-threaded, so don't bother using atomic operations while compiling it?按照上面的问题,如果答案是否定的,有没有办法告诉编译器他的程序是单线程的,所以编译时不用费心使用原子操作?
  1. It will depend on the compiler.这将取决于编译器。 Visual Studio 2017 is not smart enough. Visual Studio 2017 不够智能。 I cannot tell what clang will do (I am not using them on daily basis) but I will bet that their are not that smart either.我不知道 clang 会做什么(我不是每天都使用它们)但我敢打赌它们也没有那么聪明。 As @yachoor pointed out in comment "g++ on Linux is smart enough - it doesn't use atomic operations for std::shared_ptr if program isn't linked with pthread"正如@yachoor 在评论中指出的“Linux 上的 g++ 足够智能 - 如果程序未与 pthread 链接,它不会对 std::shared_ptr 使用原子操作”

  2. Not sure but there is no standard way to do this.不确定,但没有标准的方法来做到这一点。 Take a look at this.看看这个。 You can use std::move operator so there reference will not be increased.您可以使用 std::move 运算符,因此不会增加引用。 If that is not the case I think that there is no easy way to do this.如果不是这种情况,我认为没有简单的方法可以做到这一点。

Regarding point 2, there are other possibilities.关于第 2 点,还有其他可能性。 You can extract the pointer to that object and pass it as reference everywhere it is needed in your program.您可以提取指向该对象的指针并将其作为引用传递到程序中需要的任何地方。 As it is single threaded you should be pretty much sure about lifetime of this object.由于它是单线程的,因此您应该非常确定此对象的生命周期。 Otherwise you might want to rethink you memory ownership desing.否则,您可能需要重新考虑您的内存所有权设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM