Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In this SO question is stated that this construct prevents stack allocation of instance.

class FS_Only {
    ~FS_Only() = delete;  // disallow stack allocation
};

My question is, how does it prevents allocation? I understand, that is not possible to delete this instance, either explicitly or implicitly. But I think, that would lead to memory leak or run time error, respectively.

Are compilers smart enough to sort this out and raise compiler error? Also why would one need this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
235 views
Welcome To Ask or Share your Answers For Others

1 Answer

The destructor of a variable with automatic storage duration (i.e. a local variable) would need to run when the variable's lifetime ends. If there is no accessible destructor the compiler refuses to compile the code that allocates such a variable.

Basically the distinction between "stack allocation" (an inaccurate choice of term by the way) and free store allocation is that with local variables constructor/destructor calls always come in pairs, whereas with free store allocation you can construct an object without ever destructing it. Therefore by preventing access to the destructor your code makes it impossible to allocate a local variable of the type (if the constructor runs the destructor must also run, but there is no destructor so the program is rejected).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...