I wrote a smarter pointer class. And to make the following code correct
ZhjSmartPointer<int> a(new int);
assert(a != NULL);
I overload the != operator like this:
bool operator !=(T *ptr) const;
however, this leads to a compile error like this:
ZhjSmartPointer.h:132: note: candidate 1: bool ZhjSmartPointer::operator!=(T*) const [with T = Test] test.cpp:41: note: candidate 2: operator!=(int, int)
I'm confuse with how a ZhjSmartPointer can be transfered into an int
The Code of SmartPointer class is like this:
template <typename T>
class ZhjSmartPointer {
public:
ZhjSmartPointer();
explicit ZhjSmartPointer(T *ptr);
ZhjSmartPointer(const ZhjSmartPointer &smartPtr);
ZhjSmartPointer &operator =(const ZhjSmartPointer &smartPtr);
~ZhjSmartPointer();
operator bool() const;
T &operator *() const;
T *operator ->() const;
bool operator ==(const ZhjSmartPointer &smartPtr) const;
bool operator !=(const ZhjSmartPointer &smartPtr) const;
bool operator ==(T *ptr) const;
bool operator !=(T *ptr) const;
private:
void copyPtr(const ZhjSmartPointer &smartPtr);
void deletePtr();
T *ptr_;
size_t *refCnt_;
};
I guess because I overload the 'bool' operator, 'ZhjSmartPointer -> bool -> int' leads to this problem.Is this right?
Sorry,It is just a compile warning, not a error. Someone suggest me not overloading != with parameter(T *), after all, we already have overloaded 'bool'.It will be fine to write codes like these:
ZhjSmartPointer a(new int);
if (a) {
..........
}
intas parameter withoutexplicitcould cause that conversion. - phoeagonint(well T), but aint*(T*), so the "implicit constructor conversion" exists doesn't make much sense. What does make sense is the assumption that you allow an implicit conversion fromZhjSmartPointer<int>tointwhich would then lead to this error. Really not much you can do, apart from usingintptror removing the implicit conversion. - Voog++ 4.6.3with a warning issued. So I guess it is compiler-dependent. What's your compiler? - phoeagon