0

To be multi-thread safe, the std::shared_ptr uses atomic operations to perform reference counting. 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?
curiousguy
  • 8,038
  • 2
  • 40
  • 58
John Z. Li
  • 1,893
  • 2
  • 12
  • 19
  • 3
    It depends on the compiler and standard library, but for g++/libstdc++ see https://stackoverflow.com/a/15141844/1135979 – yachoor Mar 22 '19 at 11:00

1 Answers1

0
  1. It will depend on the compiler. Visual Studio 2017 is not smart enough. 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. 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"

  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. If that is not the case I think that there is no easy way to do this.

Regarding point 2, there are other possibilities. 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.

wdudzik
  • 1,264
  • 15
  • 24
  • 4
    g++ on Linux is smart enough - it doesn't use atomic operations for `std::shared_ptr` if program isn't linked with pthread – yachoor Mar 22 '19 at 11:17
  • @yachoor, does it mean that if a program isn't linked with pthread, shared pointer is not thread safe and cannot be used with `std::thread`? – vahancho Mar 22 '19 at 11:26
  • 1
    @vahancho If you don't link with pthread, you can't use `std::thread`. – molbdnilo Mar 22 '19 at 11:29
  • 2
    @vahancho `std::thread` in libstdc++ on linux is implemented using pthreads, so if you use `std::thread` you must link with pthread or you get linker error – yachoor Mar 22 '19 at 11:33
  • @yachoor, molbdnilo, ah, ok. Thanks. – vahancho Mar 22 '19 at 11:53