e******d 发帖数: 310 | 1 In the following code for Singleton, why will the destructor be
called again and again??
Thank you.
=============================
#include "stdio.h"
class Singleton
{
public:
static Singleton* create_obj();
~Singleton()
{
printf("Destor is called \n");
if(psig != NULL)
delete psig;
}
private:
Singleton() { printf("Contor is called \n"); }
static Singleton* psig;
};
Singleton* Singleton::psig = NULL;
Singleton* Singleton::create_ | X****r 发帖数: 3557 | 2 To delete a (pointer to) object will call its destructor, so
of course in your code there is an infinite recursion.
And you're calling a member function from a null pointer...
You would make better progress if you learn the basics of the
language first, before jumping into design patterns.
【在 e******d 的大作中提到】 : In the following code for Singleton, why will the destructor be : called again and again?? : Thank you. : ============================= : #include "stdio.h" : class Singleton : { : public: : static Singleton* create_obj(); : ~Singleton()
| e******d 发帖数: 310 | 3 Thank you so much for your explanation.
one line for creating obj is missing in the main function. But the wrong
code gives me an opportunity to learn some new stuff.
In the original code,
1. psig1 is null, but it calls ~Singleton() sucessfully, why? I am just
wondering if the reason is that ~Singleton() is a static function.
2. In the main function, we did not create any Singleton obj, so static
member psig should be NULL,
when ~Singleton()is called, "delete psig" should not be executed. and | X****r 发帖数: 3557 | 4 1. Because the way calling a non-virtual member function is implemented,
'this' (null here) is simply passed as a implicit parameter to the
function. And in your ~Singleton neither 'this' or other non-static
members (there is none) is used, so it appears to work. But strictly
speaking the behavior of your code is undefined. Don't do this.
Also, a destructor is never static. It is to 'destruct' a particular
instance 'this'.
2. Is this all of your code? Did you create the instance somewhere
else?
【在 e******d 的大作中提到】 : Thank you so much for your explanation. : one line for creating obj is missing in the main function. But the wrong : code gives me an opportunity to learn some new stuff. : In the original code, : 1. psig1 is null, but it calls ~Singleton() sucessfully, why? I am just : wondering if the reason is that ~Singleton() is a static function. : 2. In the main function, we did not create any Singleton obj, so static : member psig should be NULL, : when ~Singleton()is called, "delete psig" should not be executed. and
| e******d 发帖数: 310 | 5 Thank you. It is clear now. |
|