Passing a pointer to temporary object

丶灬走出姿态 提交于 2019-12-12 04:58:22

问题


We know that we can pass temporary objects to functions by const reference, like this:

class A
{
public:
    A(int _b = 0) 
    {
        b = _b;
    }

    int b;
};

void foo(A& a) {printf("%d", a.b);}
void cfoo(const A& a) {printf("%d", a.b);}

int main(void)
{
    //foo(A(4)); doesn't compile
    cfoo(A(5));
}

but what about passing by pointer? why does this compile?

void pfoo(A* pa) {pa->b = 19;}

int main(void)
{
    pfoo(&A(5));
}

回答1:


but what about passing anonymous variables pointer? why does this compile?

You are probably using a compiler that does not honour C++ standard.

No address of an r-value (temporary) object can be taken. That should not compile.


However, operator& can be overloaded, so that it can be invoked on a temporary object, e.g.:

struct A
{
    A* operator&() { return this; }
};

In C++11 a temporary object can be bound to an r-value reference. After that r-value reference behaves like an l-value and hence the address of a temporary object can be taken:

struct A {};

void foo(A*);

void foo(A&& a) { foo(&a); }

int main() {
    foo(A{});
}


来源:https://stackoverflow.com/questions/25907846/passing-a-pointer-to-temporary-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!