how do you add a destructor to an anonymous class in C++? like in PHP if i want to run something when my class go out of scope it'd be
$foo = new class() {
public $i=0;
public function __destruct()
{
echo "foo is going out of scope!\n";
}
};
but in C++ with normal non-anonymous classes you specify the destructor with ~ClassName(){}
, but anonymous classes doesn't have a name! so how do you add a destructor to
class {public: int i=0; } foo;
in c++? i tried using the variable name as the class name, but that didn't work:
class {
public:
int i;
~foo(){std::cout << "foo is going out of scope!" << std::endl;}
} foo;
resulting in
prog.cc: In function 'int main()':
prog.cc:51:31: error: expected class-name before '(' token
51 | class {public: int i=0; ~foo(){std::cout << "foo is going out of scope!" << std::endl;};} foo;
| ^
i also tried specifying just ~
but that didn't work either,
class {
public:
int i=0;
~(){std::cout << "foo is going out of scope" << std::endl;}
} foo;
resulted in
prog.cc:48:30: error: expected class-name before '(' token
48 | class {public: int i=0; ~(){std::cout << "foo is going out of scope" << std::endl;};} foo;
| ^