3

我在将引用计数指针<Type>类的实例放入 Array 类时遇到问题。使用调试器,似乎从未调用构造函数(这会弄乱引用计数并导致段错误)!

我的 push_back 函数是:

void push_back(const T& element)
{
    if (length >= max)
        reallocate(max > 0 ? max * 2 : 1);

    new (&data[length]) T(element);
    ++length;
}

引用计数在调用 new 之前和之后是相同的。我很确定这是问题所在,但我不知道为什么不调用构造函数。此外,Pointer::Pointer(...) 编译它是否需要一个 Pointer <T>& 或一个 const Pointer <T>& (嗯?),并且无论如何也有问题!

也许有一些关于安置新的细节我没有考虑到。如果有人有一些想法,他们将不胜感激!

编辑:[根据要求,来自指针的相关摘录]

// ...
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();
    }
// ...

我还为指针<T>& and实现了 operator = T*,以及 operator -> 和 operatorT*

4

3 回答 3

2

根据文档,应调用构造函数...您可以检查的几件事:

测试指针:

Pointer<int> p1(new int);
Pointer<int> p2(p1); // Does this call constructor properly?

测试数组:

Array<std::string> array;
std::string str("bla");
array.push_back(str); // Does this call string's constructor

那就是失败,对吧?

Array<Pointer<int> > array;
Pointer<int> p1(new int);
array.push_back(p1);

如果一切都失败了,您总是可以这样做以确保调用复制构造函数或 operator=

T* t = new (&data[length]) T();
*t = element;
于 2009-07-23T05:48:55.267 回答
2

Your comment and your code are out of sync:

//! Copy Constructor
template<class X> Pointer(Pointer<X>& other)

A constructor generated from a class template is not a copy constructor (there's a footnote in 12.8 [class.copy] that clarifies this), so won't prevent the compiler from generating a copy constructor for you. This generated constructor will be a better match for a standard copy as non-template functions are preferred to template functions in overload resolution.

It appears that you need to write an explicit copy constructor in your pointer class to get the desired effect.

于 2009-07-23T06:37:38.507 回答
0

请在此处发布您的指针类。我认为这个类中的 T 是 Pointer ?如果是这样,代码应该这样做: new (&data[length]) Pointer(element);

我很难理解..

为什么不直接做:data[length] = element; 我假设 data[length] 是指针

于 2009-07-23T06:08:56.707 回答