Hello there everyone! This is something that I don´t seem to understand: why can´t I use operator delete in the global namespace. Please bear with me as I am a C programmer trying my transition to C++. Here´s some code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class point_2d {
public:
point_2d()=default;
point_2d(double x, double y): x_{x}, y_{y} {}
// more code here
private:
double x_=.0, y_=.0;
};
point_2d * origin = new point_2d{};
delete origin; // error!
int main(){ delete origin; // Ok! }
Why is it ok to use delete inside main whereas in the global namespace every compiler I use refuse to compile (VC 2013, gcc 4.9 and LLVM 3.5).
You can't put arbitrary code in global scope in C++ or in C; writing delete statements there would be equivalent to putting if statements or while loops in the global scope, which isn't allowed. Compare delete to a call of free() in C; you can't have that in the global scope either. Does that make sense?