I am having a problem placing an instance of my reference-counting Pointer<Type>
class into my Array class. Using the debugger, it seems that the constructor is never called (which messes up the reference-count and causes a segfault down the line)!
My push_back function is:
void push_back(const T& element)
{
if (length >= max)
reallocate(max > 0 ? max * 2 : 1);
new (&data[length]) T(element);
++length;
}
The reference-count is the same before new is called as after. I'm very sure this is the problem, but I can't figure out why the constructor wouldn't be called. Additionally Pointer::Pointer(...) compiles whether it takes a Pointer<T>
& or a const Pointer<T>
& (huh?), and has the problem regardless as well!
Maybe there are some details on placement new I am not taking into account. If anyone has some thoughts, they'd be much appreciated!
edit: [as requested, a relevant excerpt from Pointer]
// ...
private:
T* p;
public:
//! Constructor
Pointer()
: p(0)
{
}
//! Copy Constructor
template<class X> Pointer(Pointer<X>& other)
: p(other.getPointer())
{
if (p)
p->incrementRef();
}
//! Constructor (sets and increments p)
Pointer(T* p)
: p(p)
{
if (p)
p->incrementRef();
}
//! Destructor (decrements p)
~Pointer()
{
if (p)
p->decrementRef();
}
// ...
I've also implemented operator = for Pointer<T>
& and T*
, as well as operator -> and operator T*