使用带有成员函数指针的std :: shared_ptr

Mag*_*nRa 4 c++ pointers

使用C指针,我可以像这样做一些事情:

#include <iostream>
#include <memory>
class Foo {
     void bar(){
     std::cout<<"Hello from Foo::bar \n";
        }
   } 

void main(){
    Foo foo; 
    Foo* foo_ptr=&foo;
    std::shrared_ptr<Foo> foo_sptr(&foo);
    void (Foo::*bar_ptr)()=&Foo::bar;
    (foo.*bar_ptr)();
    (foo_ptr->*bar_ptr)();
    //(foo_sptr->*bar_ptr)(); // does not compile for me
Run Code Online (Sandbox Code Playgroud)

如果我想使用smart_ptr而不是C指针,我会收到编译错误:

error: no operator "->*" matches these operands
        operand types are: std::shared_ptr<Foo> ->* void (Foo::*)()
(foo_sptr->*bar_ptr)();
Run Code Online (Sandbox Code Playgroud)

有没有办法让这个工作没有std :: shared_ptr :: get()?

Rei*_*ica 9

std::shared_ptr没有提供超载operator ->*.所以你必须使用get():

(foo_sptr.get()->*bar_ptr)();
Run Code Online (Sandbox Code Playgroud)

实例