Hello, I have a struct that manages window. What I want to do is, when user(It will be a library) wants to create an object, user only be allowed to create a pointer.
How can I do that?
e.g:
1 2
Window window; // It will give an error
Window *window; // no problem. This is how it should be
I saw an example of this in GLFW
1 2
GLFWwindow* window; // no problem
GLFWwindow window; // error
You can make the constructor private, and then provide a function that has permission to use that private constructor (friend), or alternatively give the class with the newly private constructor a public static function that the user can call. The user must call the function, and that function will then create the object on the heap and return a pointer. Because the user cannot call the constructor directly, they have no way to create the object on the stack.
That said, this is bad. This is dangerous. This is asking for memory leaks. At the very least, you should be using a smart pointer to avoid memory leaks.
Just to check; you know that the "no problem" code here doesn't create a GLFWwindow anywhere; doesn't create one on the heap or on the stack?
1 2
GLFWwindow* window; // no problem
GLFWwindow window; // error
I wish you had mentioned this in your original post. After all, this is a C++ forum.
I can think of one way but it's very ugly: hide the struct from the user completely and provide functions to do all the allocating/deallocating and work. Pass the structure via a void*:
1 2 3 4
void *allocWindow(); // allocates a window on the heap and returns it
void *deallocWindow(void *w); deallocate window previously allocated with allocWindow()
unsigned getWindowTop(void *w); // get coordinate of top of window
// etc.
Another way is to see if there is a function that will always be called on a window. Add code there to see if the window is on the heap. Of course that means using OS-dependent methods to get the bounds of the heap.
Or you could just put a comment in the header file saying "you must allocate this on the heap"