I recently tried to create my own common and weak pointers. Code that compiles using Visual Studio does not compile in GCC (4.5.0) with the following error:
main.cpp: In function 'int main()':
main.cpp:18:27: error: no match for 'operator=' in 'wp1 = weak_ptr<int>(((const shared_ptr<int>&)((const shared_ptr<int>*)(& sp1))))'
weak_ptr.h:59:9: note: candidate is: void weak_ptr<T>::operator=(weak_ptr<T>&) [with T = int, weak_ptr<T> = weak_ptr<int>]
Here are the most important parts of my code:
1) Weak implementation of the pointer (pay attention to the declaration operator=)
#include "smart_ptr_wrapper.hpp"
#include "shared_ptr.h"
template <typename T>
class weak_ptr {
private:
typedef smart_ptr_wrapper<T> weak_ptr_wrapper;
weak_ptr_wrapper* wrapper;
private:
void increase_reference_count() {
++(wrapper->weak_count);
}
void decrease_reference_count() {
--(wrapper->weak_count);
if (wrapper->strong_count == 0 && wrapper->weak_count == 0) {
delete wrapper;
}
}
public:
weak_ptr() : wrapper(NULL) { }
weak_ptr(const shared_ptr<T>& pointer) : wrapper(pointer.wrapper) {
increase_reference_count();
}
weak_ptr(const weak_ptr& p) : wrapper(p.wrapper) {
increase_reference_count();
}
weak_ptr& operator= (weak_ptr& p) {
if (wrapper != NULL) {
decrease_reference_count();
}
p.increase_reference_count();
wrapper = p.wrapper;
return *this;
}
~weak_ptr() {
decrease_reference_count();
}
T* get() const { return (wrapper->strong_count == 0) ? NULL: wrapper->raw_pointer; }
T* operator-> () const { return get(); }
T& operator* () const { return *get(); }
operator void* () const {
return (get() == NULL);
}
};
2) main.cpp
int main() {
shared_ptr<int> sp1(new int(4));
weak_ptr<int> wp1(sp1);
wp1 = weak_ptr<int>(sp1);
return 0;
}
Question:
Why is this happening? I'm probably pretty dumb, but I can't figure out what is wrong with this code, and cannot reveal the behavior of GCC. I would also appreciate if anyone could explain why this code compiles and why it works under MSVS (I mean, why one compiler will do fine and why the second crashes). Thank.
: - http://codepad.org/MirlNayf