Why the addresses of this two variable(i.e hoofunc
and Ctx::hookFunc4Boost
) are not same whereas the Ctx::getBoostHookFun()
return a left reference to Ctx::hookFunc4Boost
?
I intend to avoid the copy of a temporary object by returning a left reference to Ctx::hookFunc4Boost
.
Here is the code snippet:
#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;
}
Here are the outputs:
inner hookFunc4Boost:0x7fffffffdf28
outer hookFunc:0x7fffffffd540
With the help of JaMiT, I think I find the answer.
Here is a demo code(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;
}
The variable cnt
and Ctx::m_cnt
are two different variables. So their addresses should be different. It still needs to call copy constructor when invoking const int cnt = pCtx->getCnt();
. Am I right?