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;
| ^
This cannot be done in C++. However, the real C++ analogue of anonymous classes is called an anonymous namespace:
namespace {
struct foo {
// ... whatever
~foo();
};
}
// ... later in the same C++ source.
foo bar;
Now you can use and reference foo
s everywhere in this specific C++ source file. Other C++ source files may have their own anonymous namespace, with their own foo
s, without creating a conflict. The end result is pretty much the same thing as C-style anonymous structs (a.k.a. classes), except that they're not really anonymous, only their namespace is.