Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4235160
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T02:27:35+00:00 2026-05-21T02:27:35+00:00

I’ve recently been trying out shared_ptr and I’ve run across a bit of a

  • 0

I’ve recently been trying out shared_ptr and I’ve run across a bit of a weird case. What I want is a template member function which is capable of returning a shared_ptr of its derived type. I’m running visual studio 2010 which has access to some of the new c++0x standard, but I assume the boost shared_ptr behaves similarly.

This worked fine with bare pointers. I just returned a dynamic_cast<DerivedClass*>(this). I’m kind of stumped here, however, because even using enable_shared_from_this the object attempts to delete itself after the function is called (which is bad). I am probably approaching this wrong, but I’d like to work out how to simulate the bare pointer equivalent (which was working) of the following (this is the code I’m having trouble with).

//assume we have a virtual function as well.
class BaseClass : public std::enable_shared_from_this<BaseClass>
{
  ....
  template<typename DerivedClass>
  std::shared_ptr<DerivedClass> BaseClass::getThis(){
     //I had some assert code here to ensure typeid matched
     return std::dynamic_pointer_cast<DerivedClass>(shared_from_this());
  }
}

edit: It seems the function works correctly, the problem was with how I was using it. It is bad, for example to do the following:

std::shared_ptr<DerivedClass> p = std::make_shared<DerivedClass>();
p->getType<DerivedClass>->someOtherFunctionOnlyInTheDerivedClass();

This is not a problem:

std::shared_ptr<BaseClass> p = std::make_shared<DerivedClass>();
p->getType<DerivedClass>->someOtherFunctionOnlyInTheDerivedClass();

I’m not entirely sure if it’s a problem with converting to the same type, or a reference counting issue. In any case, I was doing something dumb and it broke, avoiding the unnecessary getType call at that point seems to work fine in every other case I am using it. Maybe someone can explain precisely what causes the first example to break with the second example working. I’ll assign points to that answer.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-21T02:27:36+00:00Added an answer on May 21, 2026 at 2:27 am

    To expand on Stuart’s answer and to (possibly) explain why you were crashing, my best guess is that you were calling getType on a stack-alloc’d instance. It’s a major pitfall to using enable_shared_from_this.

    #include <memory>
    
    class Base : public std::enable_shared_from_this<Base>
    {
    public:
        virtual ~Base() {}
    
        template <typename D>
        std::shared_ptr<D> getType()
        {
            return std::dynamic_pointer_cast<D>(shared_from_this());
        }
    };
    
    class Derived : public Base
    {
    public:
        void f() {}
    };
    
    int main()
    {
        std::shared_ptr<Derived> d = std::make_shared<Derived>();
        d->getType<Derived>()->f(); // fine
    
        Derived d2;
        Base* p = &d2;
        p->getType<Derived()>->f(); // will attempt to delete d2 after f() returns.
    
        return 0;
    }
    

    The reason this occurs is because the reference count of d2 is zero when it’s on the stack. Calling shared_from_this returns a shared_ptr that increments the reference count to one. Once this pointer goes out of scope, it decrements its count to zero, which then attempts to delete the instance, which, of course, is on the stack.

    The only way that I can think of protecting yourself from this, off the top of my head, is to make all constructors protected or private and provide static functions that dynamically allocate any instances, returning shared_ptrs, of course.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I want to construct a data frame in an Rcpp function, but when I
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
I am trying to understand how to use SyndicationItem to display feed which is
I have a jquery bug and I've been looking for hours now, I can't
Basically, what I'm trying to create is a page of div tags, each has
I have a French site that I want to parse, but am running into

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.