0

Have a look at the Reset function below. I know calling constructors and destructors for this can be dangerous, but I really cannot find what is wrong when used as below. I'm asking this here because I couldn't find any related materials with Google. All I can find is that don't call the constructor within another constructor, and I obviously agree with that. But isn't it safe to call the constructor right after the destructor in a member function?

template<typename T>
class Array{
private:
    T* m_p;

    Array(const Array&);
    Array& operator=(const Array&);

public:
    Array(){
        m_p=0;
    }

    Array(int length):
    m_p(new T[length]){}

    ~Array(){
        delete[] m_p;
    }

    void Reset(int length){
        this->~Array();
        new(this) Array(length);
    }
};
  • 1
    related:[Can I get a fresh start in C++ without failing again?](http://stackoverflow.com/q/8829548/33499) – wimh May 23 '15 at 20:58

2 Answers2

1

Even if your favorite implementation allows you to do such, it is still an extremely bad practice to do it. What you need to consider is mainly 2 things:

Object is not constructed properly until the constructor ends.

Object should not be accessed after you call its destructor.

Playing tricks with constructor and destructor is not a good idea. They are there to introduce and remove the object respectively. Using them more than these roles indicates that your design is somewhat problematic. On the other side of the coin, member functions shouldn't call its object's destructor, either. Even if it works, it is still a design problem.

Community
  • 1
  • 1
Seçkin Savaşçı
  • 3,446
  • 2
  • 23
  • 39
0

This code

void Reset(int length){
    this->~Array();
    new(this) Array(length);
}

Is bad.

Why not

void Reset(int length) {
   delete[] m_p;
   m_p = new T[length];
}

or just use std::vector

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
  • `std::vector` is just too heavy to use in my case. So I'm asking 'why' is it bad? –  May 23 '15 at 20:59
  • 2
    1. Why is it too "heavy"? 2. Getting that habit of calling constructors/destructor is just bad - You get unintended consequences (destructor/constructors do things behind the scenes like memory management). – Ed Heal May 23 '15 at 21:05