1

In this code, the line (iter->second)(); calls the function reset(new childClass()). Is this correct ? If this is the case, it is called on which object ?


class BaseClass{
public:
    virtual void foo() { std::cout << "base" << std::endl;}
};

class childClass : public BaseClass {
public:
    virtual void foo() { std::cout << "derived" << std::endl;}
    ~childClass () {
        std::cout << "childClass destructor" << std::endl;   
    }
};

int main()
{
    typedef std::map<std::string, boost::function<void()>> Map_t;

    Map_t g_cmdMap = map_list_of( "cmd",
                boost::bind( static_cast<void( boost::shared_ptr<BaseClass>::* )()>( &boost::shared_ptr<BaseClass>::reset ), 
                  boost::shared_ptr<BaseClass>(new childClass() ) )) ;

    std::map<std::string, boost::function<void()>>::iterator iter;
    iter = g_cmdMap.find( "cmd" );
    (iter->second)();

    return 0;
}

1 Answer 1

2

the line (iter->second)(); calls the function reset(new childClass()). Is this correct?

No, it invokes reset(). If you want it to be called as reset(new childClass()), you need to pass new childClass() to boost::bind as argument like

boost::bind( static_cast<void( boost::shared_ptr<BaseClass>::* )(BaseClass*)>( 
               &boost::shared_ptr<BaseClass>::reset ), 
             boost::shared_ptr<BaseClass>(new childClass() ),
             new childClass() )

Note that new childClass() itself is evaluated when boost::bind is invoked, not the functor is invoked.

Or you can add a placeholder, and pass new childClass() when call the functor.

it is called on which object ?

It's called on the object copied from the argument passed to boost::bind, i.e. boost::shared_ptr<BaseClass>(new childClass() ).

Sign up to request clarification or add additional context in comments.

3 Comments

Even then it would not be equivalent to reset(new childClass()); rather it would be equivalent to reset(tmObj); where tmpObj is childClass object created when bind() was called.
Is it possible to retrieve the tmpobj ? If this is the case how can we do that ? And is it possible to call reset on an exisiting object and not a tmpobj ? Thanks All for you support.
It's possible by doing someting like this : boost::bind( static_cast<void( boost::shared_ptr<BaseClass>::* )(BaseClass*)>( &boost::shared_ptr<BaseClass>::reset ), &pBaseClass, new childClass() );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.