且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将指针传递到临时对象

更新时间:2023-11-11 23:23:46


但是如何传递匿名变量指针?为什么会编译?


你可能使用的编译器不符合C ++标准。



可以不使用r值(临时)对象的地址。这不应该编译。






但是, operator& 重载,以便它可以在临时对象上调用,例如:

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




在C ++ 11中,临时对象可以是绑定到r值引用。之后,r值引用的行为类似于l值,因此临时对象的地址可以取:

  struct A {}; 

void foo(A *);

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

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


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));
}

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{});
}