From -628006875195074669
X-Google-Thread: f78e5,6dda3f736a89f6d8
X-Google-NewGroupId: yes
X-Google-Attributes: gid7894ca11fe,domainid0,public,usenet
X-Google-Language: ENGLISH,ASCII-7-bit
Path: g2news1.google.com!news1.google.com!news.glorb.com!news.alt.net!frodo.cs.rpi.edu!not-for-mail
From: lucdanton <lucdanton@free.fr>
Newsgroups: comp.std.c++
Subject: Re: shared_from_this() from constructor
Date: Thu, 26 Aug 2010 13:10:22 CST
Organization: http://groups.google.com
Lines: 48
Sender: cppmods@cs.rpi.edu
Approved: james.dennett@gmail.com
Message-ID: <a760875f-a836-4b3a-9c14-ab1f2ff558a7@i31g2000yqm.googlegroups.com>
References: <de2bf2a0-c5b7-4ba2-a4e2-85842f0a0c4b@q22g2000yqm.googlegroups.com>
NNTP-Posting-Host: netlab.cs.rpi.edu
Content-Type: text/plain; charset=ISO-8859-1
To: (Usenet)
Return-Path: <cppmods@ruralroute.cs.rpi.edu>
X-Original-Date: Thu, 26 Aug 2010 03:46:17 -0700 (PDT)
X-Submission-Address: std-c++@netlab.cs.rpi.edu
Xref: g2news1.google.com comp.std.c++:2911

On Aug 26, 12:49 am, Florian Goujeon <florian.gouj...@42ndart.org>
wrote:
> The current GCC's implementation doesn't allow to call
> shared_from_this() from the class' constructor, just like the original
> Boost's implementation.
> Is this a standard-compliant behavior? The current draft doesn't talk
> about this.
> I hope it's not. This is really annoying...

If what you're trying to do (but really, I can't tell if you don't) is
to register new objects somewhere, then the usual solution is to
separate concerns:
- have constructors private or protected: their concern is to setup
new instances with correct invariants (nothing unusual here)
- expose a (or several) public factory function that return shared_ptr
to new instances: their concern is to register new instances

Could be as simple as:

class Something;

/* could be part of the class, too */
void add_to_registry(std::shared_ptr<Something> const&);

/*  enabled_shared_from_this might or might not be necessary */
class Something: public std::enable_shared_from_this {
 /* whatever */

 template<typename ...T>
 static std::shared<Something> make(T&& ...t)
 {
   auto p = std::make_shared<Something>(std::forward<T>(t)...);
   add_to_registry(p);
   return p;
 }

};

Or maybe Something::make can return a reference to *p and the registry
takes care of lifetime management, if that's what you want.


--
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@netlab.cs.rpi.edu]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]



