关于类型为 boost::function 的 return 对象的对象地址的问题 &

Question about the object adress of a return object with the type of boost::function &

为什么这两个变量的地址(即hoofuncCtx::hookFunc4Boost 不一样Ctx::getBoostHookFun() return 左引用 Ctx::hookFunc4Boost?

我打算通过 return 对 Ctx::hookFunc4Boost 的左引用来避免复制临时对象。

这是代码片段:

#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <iostream>

class Ctx
{
public:
const boost::function<void((void*))>& getBoostHookFun(void)
{
    std::cout << "inner hookFunc4Boost:" << (void*)(&hookFunc4Boost) << std::endl;
    return hookFunc4Boost;
}

private:
boost::function<void(void*)> hookFunc4Boost;

};

int main()
{
    Ctx ctx;
    Ctx *pCtx = &ctx;
    const boost::function<void((void*))> hookFunc = pCtx->getBoostHookFun();
    std::cout << "outer hookFunc:" << (void*)(&hookFunc) << std::endl;
}

输出如下:

inner hookFunc4Boost:0x7fffffffdf28
outer hookFunc:0x7fffffffd540

要避免复制,只需将您的变量更改为引用即可:

const auto& hookFunc = pCtx->getBoostHookFun();

在 JaMiT 的帮助下,我想我找到了答案。

这里是演示代码(https://coliru.stacked-crooked.com/view?id=12bc35c31c9eb605):

#include <iostream>

class Ctx
{
public:
Ctx(int cnt):m_cnt(cnt){}

const int& getCnt(void)
{
    std::cout << "inner:" << (void*)&m_cnt << std::endl;
    return m_cnt;
}

private:
int m_cnt;

};

int main()
{
    Ctx ctx(6);
    Ctx *pCtx = &ctx;
    const int cnt = pCtx->getCnt();
    std::cout << "outer:" << (void*)&cnt << std::endl;
}

变量cntCtx::m_cnt是两个不同的变量。所以他们的地址应该不同。调用const int cnt = pCtx->getCnt();时仍然需要调用拷贝构造函数。我说得对吗?