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 6717489
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T08:51:31+00:00 2026-05-26T08:51:31+00:00

Please consider the following simplified example: #include boost/shared_ptr.hpp #include boost/smart_ptr/enable_shared_from_this.hpp using namespace boost; class

  • 0

Please consider the following simplified example:

#include "boost/shared_ptr.hpp"
#include "boost/smart_ptr/enable_shared_from_this.hpp"

using namespace boost;

class State : public boost::enable_shared_from_this<State>
{
public:
    shared_ptr<State> GetSelf()
    {
        return shared_from_this();
    };
    // returns following state
    virtual shared_ptr<State> Execute() = 0;
};

template<typename T>
shared_ptr<T> Create()
{
    return shared_ptr<T>(new T);
}

class MyState2;

class MyState1 : public State
{
    virtual shared_ptr<State> Execute()
    {
            if (change of state)
          return Create<MyState2>();
            else
              return GetSelf();
    };
};

class MyState2 : public State
{
    virtual shared_ptr<State> Execute()
    {
            if (change of state)
          return Create<MyState1>();
            else
              return GetSelf();
    }; 
};

int main(int argc, char* argv[])
{
    shared_ptr<State> pCurrentState = Create<MyState1>();  // <-- OK
//  State* pCurrentState(new MyState1);                    // <-- Runtime error
    while (...)
      pCurrentState = pCurrentState->Execute();

    return 0;
}

The State-class is part of a ‘framework’. It is the base for user defined states in a lightweight state machine, where each state returns its follower state. In case the state does not change, it returns itself. The framework user may arbitrarily derrive from class State. Obviously it is not allowed to create ‘uncontrolled’ instances of derrived classes (would result in runtime error if GetSelf() is invoked). To point the user to the right direction, a Create() function template is provided to create ‘controlled’ instances. Since I want to make usage as foolproof as possible, how can I make sure a user won’t create any instances of derrived states which are not under shared_ptr control? Or at least give a meaningful error message (at compile time?) if he does so.

Thanks for your help!

  • 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-26T08:51:32+00:00Added an answer on May 26, 2026 at 8:51 am

    The simplest way to prevent unmanaged instances is to make the constructor of each derived class private. Your factory function will need to be either a friend or a member of the class it’s creating; if you want to keep your factory template, then it will need to be declared before the derived classes in order to make it a friend:

    template<typename T>
    shared_ptr<T> Create()
    {
        return shared_ptr<T>(new T);
    }
    
    class Derrived : public Base
    {
    private:
        friend shared_ptr<Derrived> Create<Derrived>();
        Derrived() {}
        // Client implementation goes here
    };
    

    However, I would usually recommend that you don’t force a class to be managed in a particular way. You should only do something like this if the classes themselves require that they are managed by shared pointers in order to function correctly (that is, they need to call shared_from_this() from their member functions for some reason). Otherwise, just organise your framework so that it uses shared pointers, and anyone using the framework will have to do likewise with no need for strange enforcement mechanisms. There should be no need for GetSelf() at all, since you’ll always have a shared pointer available to copy if you have access to an object at all, and no need for enable_shared_from_this unless the classes need to access shared pointers internally (which is rather an unusual thing to do).

    UPDATE: In your use case, I don’t think it’s possible for the base class to enforce the use of shared pointers (but please correct me if I’m wrong). It might make sense to enforce the use of shared pointers when calling the functions that require them. You’ll be able to create unmanaged objects, but not do anything dangerous with them.

    class State : public boost::enable_shared_from_this<State>
    {
    public:
        // returns following state
        friend shared_ptr<State> Execute(shared_ptr<State> state) {
            return state->Execute();
        }
    private:
        virtual shared_ptr<State> Execute() = 0;
    };
    
    class MyState : public State
    {
        shared_ptr<State> Execute() {return shared_from_this();}
    };
    
    int main(int argc, char* argv[])
    {
        shared_ptr<State> state1(new MyState);  // <-- OK
        State * state2(new MyState);            // <-- OK, but can't be used
        Execute(state1);                        // <-- OK
        // Execute(state2);                     // <-- Error
        // state2->Execute();                   // <-- Error
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

please consider following code #include <iostream> using namespace std; class Digit { private: int
Please consider the following three simplified files: student.h: #ifndef STUDENT_H #define STUDENT_H #include course.h
Please consider the following code: public class Person ( public string FirstName {get; set;}
Please consider the following java source: package com.stackoverflow; public class CondSpeed { private static
Please consider the following simple use case: public class Foo { public virtual int
Please consider the following three .NET types: I have an interface, an abstract class,
Please consider the following table (created using a corresponding entity) request ------- id requestor
Please consider the following code: class Abase{}; class A1:public Abase{}; class A2:public A1{}; //etc
Please consider the following code and the explanation from this Mozilla tutorial Using web
I have an app that's about presenting fictional simplified cities. Please consider the following

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.