I'm looking at the Clang Thread Safety Analysis feature with Clang 7.0
However, I'm getting an error when I attempt to use the PT_GUARDED_BY annotation with shared_ptr data members:
error: 'pt_guarded_by' only applies to pointer types; type here is 'shared_ptr<MyClassType>' [-Werror,-Wthread-safety-attributes]
This is a bit confusing to me, as the documentation says "PT_GUARDED_BY is ... intended for use on pointers and smart pointers.", and even gives an example which uses std::unique_ptr (using basically the same syntax I'm using).
Is std::shared_ptr incompatible with Clang's thread safety analysis, or is there something else going on here? How should I be stating that the pointed-to class shouldn't be accessed without holding a lock on the associated mutex?
(This is on Linux using GCC's libstdc++ standard library, if it matters.)
After some experiments, it looks like this only happens if the shared_ptr is a member variable, not a global.
#include "mutex.h" // The suggested mutex.h file from the Clang Thread Safety Analysis page
#include <memory>
Mutex mu;
std::shared_ptr< int > toplevel PT_GUARDED_BY(mu); // Okay
class Wrapper {
public:
std::shared_ptr< int > member PT_GUARDED_BY(mu); // Results in error
};
void test() {
Wrapper wrapped;
wrapped.member = std::shared_ptr< int >( new int ); // Should be OK
*wrapped.member = 42; // Should raise warning
}
I'll note that if I swap out unique_ptr for the shared_ptr both the global and the member variable work fine.