POV-Ray : Newsgroups : povray.off-topic : Teach yourself C++ in 21 days : Re: Days 1-5 Server Time
29 Jul 2024 20:23:05 EDT (-0400)
  Re: Days 1-5  
From: Warp
Date: 20 Apr 2012 12:06:00
Message: <4f918968@news.povray.org>
Invisible <voi### [at] devnull> wrote:
> >    In the code above where the returned object is destroyed, at no point do we
> > have a full definition of 'MyClass'. Nevertheless, when the std::shared_ptr
> > that's managing it goes out of scope, it will delete it and its destructor
> > will be called. It achieves this through template magic.

> Sure. When the template expands, we /do/ have the full class spec, so it 
> works. (At least, I'm presuming that's what happens.)

  The std::shared_ptr object in that example doesn't see the complete
definition of the class at any moment, because it hasn't been defined.
It gets initialized with another instance of std::shared_ptr (which was
created in that function somewhere else), but it itself doesn't see the
full definition of the class it's managing.

  To recapitulate:

//---------------------------------------------------------------------
class MyClass; // incomplete type

// A function somewhere else that returns a std::shared_ptr object:
std::shared_ptr<MyClass> foo();

void bar()
{
    std::shared_ptr<MyClass> ptr;
    // *this* shared_ptr object does not see a MyClass definition
    // at any point

    ptr = foo();
    // The shared_ptr returned by foo() is assigned to it.

    // Now when bar() ends, 'ptr' will destroy the object.
    // And properly at that. The destructor will be called ok.
    // Yet 'ptr' never sees the full definition of 'MyClass'.
}
//---------------------------------------------------------------------

  Even though 'ptr' above at no point sees the full definition of
'MyClass', it just works. It does so by employing template magic.

-- 
                                                          - Warp


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.