0

I'm trying to create a vector of tensors and I'm representing the tensors in 1D. I created a struct that contains a dynamically allocated array, a row and a column data (for out of bounds checking later).

struct TensorPtrManaged1D 
{
    double* m_tensorPtr;
    unsigned m_row;
    unsigned m_column;

    TensorPtrManaged1D(unsigned rowNum, unsigned colNum) {
        m_row = rowNum;
        m_column = colNum;
        m_tensorPtr = new double[rowNum * colNum];
        for (unsigned i = 0; i < rowNum; ++i){
            for (size_t j = 0; j < colNum; j++){
                m_tensorPtr[i * colNum + j] = 1;
            }
        }
    }
    ~TensorPtrManaged1D() { delete[] m_tensorPtr; }
};

If I create a single object it works fine, but if I put the same object in a vector, then whenever the destructor is called, it throws an exception: "*.exe has triggered a breakpoint. occurred"

TensorPtrManaged1D t7(3, 2);             //This executes and cleans up the memory without leak
vector < TensorPtrManaged1D > t7v(1,t7);    //This produces the exception, once it goes out of scope

Side note: while implementing it I found out that I lose all the speed advantage of direct array access once I put it in a vector, so I could achieve similar speed with a vector of vectors. However I don't understand why the struct doesn't get deleted without a problem when the destructor works otherwise.

  • 1
    If you have a vector of structs, why don't your structs contain a vector of doubles? – NathanOliver Apr 13 '20 at 14:38
  • 1
    What you have here is a rule of three violation (don't have a proper copy constructor in this case). If you switch to having a vector member, that will fix that for you (since vector "does the right thing") – NathanOliver Apr 13 '20 at 14:39
  • Might be unrelated, but i think that this line m_tensorPtr[i * colNum + j] = 1; goes out of bounds because (i*colnum+j) >= (rowNum * colNum) – MTilsted Apr 13 '20 at 14:40
  • *while implementing it I found out that I lose all the speed advantage of direct array access once I put it in a vector* -- Are you running a release, optimized version of your code? I bet you are not. If you're running a "debug", unoptimized version, then that is probably why you are seeing differences in the speed. You basically introduced bugs in your code when you changed from `vector` to pointers, for absolutely no reason. – PaulMcKenzie Apr 13 '20 at 14:56
  • Part of the reason was to play around with dynamic arrays to better understand memory management, the other part was wrongly believed speed difference (which the release version solved completely). It doesn't go out of bounds if I keep in mind that that max of i is rowNum-1 and max of j is colNum-1. In that case the last element is ((rowNum-1)*colNum+colNum-1), which is (rowNum*colNum-1). Thanks for all the answers, I will upvote when I can. – Nem Denemam Apr 14 '20 at 16:12

0 Answers0