Reputation: 96241
Is there a way with g++ to detect when you declare a class member as a (const) reference to a shared_ptr
? I can't see a time when this would ever be useful, but if you accidentally declare the member as a reference you can wind up with some hard-to-find bugs should your reference count reach zero prematurely (because the member isn't holding by value).
Or is this a case where you just write code carefully and rely on peer review?
EDIT: I'm thinking of something along the lines of the printf
format string checks/warnings where specific checks are made. For example something that checks for shared_ptr
, not a general "reference member" warning.
Upvotes: 0
Views: 152
Reputation: 69988
No compiler would provide a facility to find if a variable is a reference or not. Creating a reference variables is a very trivial operation and most of the time the intention would be genuine. It will be irritating to get compile warnings for all references present in the code.
The good way to find out if a variable is wrongly declared a reference is to have a peer review.
However, if you want to detect it on your own, there is one hack I can think of now. we can leverage the fact that a reference has to be always initialized in a constructor. You can create a common constructor with intentionally weird syntax for all classes. Example:
#define REFERENCE_CHECK(CLASS) CLASS(int***, char***)
class A { // case [1]
REFERENCE_CHECK(A) {}
};
class B { // case [2]
X &p; // genuine reference
REFERENCE_CHECK(B) : p(*new X) {} // register with the constructor
};
class C { // case [3]
shared_ptr<int> &p;
REFERENCE_CHECK(C) {} // compiler error, because 'p' is not registered
};
This is a pseudo code; remember that if needed you may have to register base classes and virtual classes also separately.
Upvotes: 1