Re: Undefined reference to...
On Nov 11, 10:58 am, Andrea Crotti <andrea.crott...@gmail.com> wrote:
James Kanze <james.ka...@gmail.com> writes:
Just for the record, that's *not* a Meyers' singleton, or any
other type of singleton. (The first condition to be a singleton
is that there is no way of getting more than one instance. In
a Meyers' singleton, this is done by making the object
noncopyable, and the constructor private. Which, of course,
excludes derivation, unless you make the derived class
a friend.)
However, what you've just shown *is* the closest working
approximation of what he seems to be trying to do. Unless he
actually wants more than one instance---it's not really clear.
For more than one instance, he'd need a factory function, e.g.
class Base
{
public:
virtual void printOut() = 0;
static std::auto_ptr<Base> getLower();
};
class Extended: public Base
{
public:
void printOut() { cout << "hello"; }
};
std::auto_ptr<Base> Base::getLower()
{
return std::auto_ptr<Base>( new Extended );
}
Ah nice I like this solution, so I can do something like
auto_ptr<Base> Base::getLower() {
auto_ptr<Base> val(new Extended);
return val;
}
int main() {
auto_ptr<Base> b = Base::getLower();
b->printOut();
delete b.release();
return 0;
}
right?
The delete if I got it it's not normally needed since when the
auto_ptr goes out of scope the object pointed is delete
automatically, right?
Exactly.
In a lot of shops, returning an std::auto_ptr is a convention
for saying that you're transfering the responsibility of the
delete. This is why boost::shared_ptr has a constructor which
takes an auto_ptr, for example. It's a fairly good convention
for objects which don't really manage themselves.
--
James Kanze