将指针传递到临时对象 [英] Passing a pointer to temporary object

查看:151
本文介绍了将指针传递到临时对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道我们可以通过const引用将临时对象传递给函数,如下所示:

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

int b;
};

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

int main(void)
{
// foo(A(4));不编译
cfoo(A(5));
}

但是通过指针传递呢?
为什么要编译?

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

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


解决方案


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


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



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






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

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






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

这篇关于将指针传递到临时对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆