In C++, can I create a struct that can only be dynamically allocated? I want to enforce a way to make sure that the programmer cannot statically allocate this struct because doing so would lead to a dangling pointer since I need to use the contents of the pointer outside of its scope.
You can make a struct
of a private constructor so no one can create from it, then make a friend
function that creat a dynamically allocated object and returns a pointer to it, as follows.
#include <iostream>
struct A{
~A() {
std::cout << "\nA has been destructed";
}
private:
A(/*args*/) {
std::cout << "\nA has been created";
}
friend A* creatA(/*args*/);
};
A* creatA(/*args*/){
return new A(/*args*/);
}
int main()
{
A* ptr = creatA();
delete ptr;
}
This can be better using smart pointers and @Peter suggestiion
#include <iostream>
#include <memory>
struct A{
A(/*args*/) {
std::cout << "\nA has been created";
}
friend std::default_delete<A>;
private:
~A() {
std::cout << "\nA has been destructed";
}
};
int main()
{
std::unique_ptr<A> ptr = std::make_unique<A>(/*Args*/);
}