Home  >  Q&A  >  body text

c++11 - c++ 如何获取成员函数的地址?

1.比如如下代码, FuncA是类A的成员函数, 那么&f1FuncA这个函数的地址么?

    function<void (int)> f1;
    A a;
    auto fun = std::bind(&A::FuncA, a, std::placeholders::_1);
    f1 = fun;

2.对于这个函数的地址, 有没有可能是变化的? 其实我是想知道, 可执行程序在运行的时候,会加载很多动态库

那么, 这个加载的过程是动态的(这时候函数的地址肯定不一样了) 还是只加载一次(函数地址固定)?

更新一个问题, 详细见1L评论.

类A里面有我的待测函数toBeTest, 单元测试的时候,里面调用了func
而后者这个函数里面有一堆调用了第三方或者系统函数,不方便mock或者成本太高.
那么,看到有人给出的一种方案是A中构造一个mock_func的打桩的函数, ut执行 的时候取两个函数的地址,替换一下。
也就是原来调用func的地方都调用mock_func ut只测试了关心的部分.

这种场景下, 还有别的什么方案么?

mock_func(){

return true; }
阿神阿神2764 days ago584

reply all(3)I'll reply

  • 阿神

    阿神2017-04-17 13:12:24

    This depends on several situations. If it is just an ordinary function, then the pointer obtained is indeed the address. If that happens to be a virtual function, and your class also includes several virtual base classes, then the size of this "pointer" may be as much as 4sizeof(void), and a lot of data is recorded in it. Including how to transfer from the pointer of this class to the pointer of the grandchild class, how to find the corresponding slot on the virtual table, etc.

    I want to popularize a piece of knowledge here. If my program writes like this:

    class A
    {
    public:
        virtual void F();
    };
    
    class B : public A
    {
    public:
        void F()override;
    };
    
    class C : public A
    {
    public:
        void F()override;
    };
    

    Then

    auto pf = &A::F;
    A* b = new B();
    A* c = new C();
    (b->pf)(); // 将会调用B::F
    (c->pf)(); // 将会调用C::F
    

    In order to complete such a function, pf is definitely not something as simple as a void* structure. So that's why C++ doesn't allow you to cast a member function pointer to void* under any conditions.

    reply
    0
  • 黄舟

    黄舟2017-04-17 13:12:24

    1. Yes.

    2. The principle of dynamic libraries is to only record the offset of the function. When loading, the starting address of the library is added, and it is fixed after loading.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:12:24

    The address is different each time it is run, and the address is fixed during a run

    reply
    0
  • Cancelreply