Is this a bad practice? It seems very hacky.
It. If the class goes out of scope before the pointer, the member variable will no longer exist, but the pointer to it still exists. Any attempt to dereference the destruction of the post-pointer class will result in undefined behavior β this can lead to failure or can make it difficult to find errors when arbitrary memory is read and processed as a BigObject.
if he considers using some smart pointer
Using smart pointers, in particular std::shared_ptr<T> or a forced version, will technically work here and avoid potential failure (if you select it through the general pointer constructor), but it also confuses who the pointer belongs to - the class or the caller? Also, I'm not sure if you can just add an object pointer to a smart pointer.
Both of these points relate to the technical problem of getting a pointer from a class, but the real question should be βwhy?β. like in "why are you returning a pointer from a class?" There are times when this is the only way, but more often than not you need to return a pointer. For example, suppose a variable is to be passed to the C API, which takes a pointer to this type. In this case, you are probably better encapsulating the C call in the class.
user257111
source share