ProgrammingHardProduct-company placement · C++

What is wrong with this program?

What is wrong with this program?
struct Buf {
    int* p;
    Buf() : p(new int[4]) { }
    ~Buf() { delete[] p; }
};
int main() { Buf a; Buf b = a; }
  1. A. Nothing; the implicit copy constructor duplicates the array
  2. B. The implicit copy shares the pointer, so the same array is deleted twice: undefined behaviour
  3. C. It fails to compile because Buf has no copy constructor
  4. D. Only a memory leak: b's array is never freed

Correct answer: B. The implicit copy shares the pointer, so the same array is deleted twice: undefined behaviour

The compiler-generated copy constructor copies the pointer value (shallow copy). Both destructors then delete[] the same block. The Rule of Three: a class that needs a destructor usually also needs a copy constructor and copy assignment (or must delete them).

More OOP with C++ and Java questions

Exams that ask this topic