Pointer to class data member “::*”

后端 未结 15 1640
清歌不尽
清歌不尽 2020-11-21 11:47

I came across this strange code snippet which compiles fine:

class Car
{
    public:
    int speed;
};

int main()
{
    int Car::*pSpeed = &Car::speed;
         


        
15条回答
  •  死守一世寂寞
    2020-11-21 12:07

    A realworld example of a pointer-to-member could be a more narrow aliasing constructor for std::shared_ptr:

    template 
    template 
    shared_ptr::shared_ptr(const shared_ptr, T U::*member);
    

    What that constructor would be good for

    assume you have a struct foo:

    struct foo {
        int ival;
        float fval;
    };
    

    If you have given a shared_ptr to a foo, you could then retrieve shared_ptr's to its members ival or fval using that constructor:

    auto foo_shared = std::make_shared();
    auto ival_shared = std::shared_ptr(foo_shared, &foo::ival);
    

    This would be useful if want to pass the pointer foo_shared->ival to some function which expects a shared_ptr

    https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr

提交回复
热议问题