requiring a heap-based objects

E

ES Kim

MEC++ Item 17 explains how to require an object be constructed only
on heap. No automatic, no static objects, that is. But I can't
find how to enforce the requirement for derived classes too.

1. make the base destructor private
No class can be derived from the base. Game over.

2. make the base destructor protected
Derived destructors should be also protected to meet the requirement,
but all bets are off once you forget to declare explicit destructor.
(It's the way most of us do most of the time.)

Any suggestion to enforce the requirement?
 
M

Maxim Yegorushkin

MEC++ Item 17 explains how to require an object be constructed only
on heap. No automatic, no static objects, that is. But I can't

Why would you want to do that?
find how to enforce the requirement for derived classes too.

1. make the base destructor private
No class can be derived from the base. Game over.

2. make the base destructor protected
Derived destructors should be also protected to meet the requirement,
but all bets are off once you forget to declare explicit destructor.
(It's the way most of us do most of the time.)

Another way is to provide interfaces and factory functions, so that a user
has no way to create an object but to invoke the factory:

struct some
{
virtual ~some() {}
virtual void foo() = 0;
};
std::auto_ptr<some> create_some();
 
H

Hendrik Schober

ES Kim said:
MEC++ Item 17 explains how to require an object be constructed only
on heap. No automatic, no static objects, that is. But I can't
find how to enforce the requirement for derived classes too.
[...]

Wouldn't this work

class heap_base {
public:
void destroy() {delete this;}
private:
virtual ~heap_base() {}
};

or am I missing something?

Schobi

--
(e-mail address removed) is never read
I'm Schobi at suespammers dot org

"Coming back to where you started is not the same as never leaving"
Terry Pratchett
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,297
Messages
2,571,530
Members
48,250
Latest member
Bette22B13

Latest Threads

Top