don't tell him that he shouldn't learn the basics if he is interested...
I think it is quite important to learn the old c-stuff to have a better understanding about the c++ standard libary.
Nah, that's not completely the same.
new constructs an object on the heap and calls the constructor for that object.
Malloc just allocates memory of the desired size (and does not call the constructor).
You try to invoke the constructor in the for loop after the allocation of the memory and this simulates the behaviour quite good, but you have to be careful about doing that, excepecially when managing Memory in that class.
The allocated memory should be deleted when the destructor is invoked and the location where x[i] points to is immediately destroyed after it is being initialized because the rvalue object Class() is on the Stack and goes out of scope in each iteration of the loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
// Example program
#include <iostream>
class Class
{
public:
Class() {std::cout << "ctor" << std::endl;}
Class& operator=(const Class&) {std::cout << "copy assignment" << std::endl; return *this;} // invoked when not using c++11
Class& operator=(Class&&) {std::cout << "move assignment" << std::endl; return *this;} // invalid when not using c++11
~Class() {std::cout << "dtor" << std::endl;}
};
int main()
{
std::cout << "malloc" << std::endl;
// Construction
Class* x = (Class*)malloc(sizeof(Class) * 3);
for (uint i = 0; i < 3; i++) x[i] = Class(); // prints ctor, move assignment and dtor 3 times
// Destruction
for (uint i = 0; i < 3; i++) x[i].~Class(); // prints 3* dtor
free(x);
std::cout << "\nnew" << std::endl;
x = new Class[3];
delete[] x;
// prints 3* ctor and 3* dtor
}
|
You ended up constructing 3 elements with malloc and deleting 6 of them, this shouldn't be what you want.
Note that there is no c-only-way to call a constructor because constructors didn't exist in C.
Therefore C++ introduced the keyword new to construct the objects on the heap.
C++ also introduced placement new to initialize objects on the heap when the memory is allready allocated:
for (uint i = 0; i < 3; i++) new((void*)&x[i]) Class();