How to make an object must created in heap

closed account (DEhqDjzh)
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  
Last edited on
closed account (DEhqDjzh)
@Repeater will it be compatible with C(The Window struct must be compatible with c)? if yes can you show it as code please ?
Structs in C do not have constructors (or any other member functions). C has no classes.

Explain the "compatible with C" requirement.
closed account (DEhqDjzh)
I mean is that code will work with C ?
What does that mean? Do it mean you're going to compile this with a C compiler?
closed account (DEhqDjzh)
@repeater
yes, with a C compiler!
Last edited on
So you need C code (not C++ code) that will enforce a struct being created only on the heap?
closed account (DEhqDjzh)
@Repeater Yes! Exactly that!
yes, with a C compiler!

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"
closed account (DEhqDjzh)
Thank you all!
Topic archived. No new replies allowed.