There was a problem with the placement-new!

I had a problem placing an instance of the Reference-counting Pointer <Type>class in an Array class. Using a debugger, it seems that the constructor is never called (which will ruin the reference count and call segfault on the line)!

My push_back function:

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 as how new is called after. I am very sure that this is a problem, but I cannot understand why the constructor will not be called. Also, the pointer :: Pointer (...) compiles whether the <T>& pointer or the const <T>& pointer (yes?) Is required , and there is a problem no matter how good!

Perhaps there are some details on the placement of new ones, which I do not take into account. If anyone has any thoughts, they will be very grateful!

edit: [ , ]

// ...
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> & T*, → T*

+3
3

:

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

, , ( 12.8 [class.copy], ), . , .

, , .

+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 constructor

, ?

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

, , =

T* t = new (&data[length]) T();
*t = element;
+2

, Pointer. , T - ? , : new (& data [length]) ();

.

: data [length] = element; , [] -

0

Source: https://habr.com/ru/post/1713307/


All Articles