簡體   English   中英

為什么我不能將地址作為參考傳遞?

[英]Why Can't I pass an Address As a Reference?

我有一個函數,它將一個指針作為引用參數,但我無法將&my_variable傳遞給該函數。 我收到的錯誤是cannot convert parameter from my_class* to my_class*&使用VS2010 cannot convert parameter from my_class* to my_class*&

為什么不允許這樣做?

class my_class
{
public:
    my_class();
    my_class(my_class* &parent);
};

-

int main()
{
    my_class a;
    my_class b(&a);                   // Not legal

    // ---
    my_class a;
    my_class* a_ptr = &a;
    my_class b(a);                    // Legal

    // ---
    my_class* a = new my_class;
    my_class* b = new my_class(a);    // Legal
}

表達式地址的結果是右值。 因此,您無法將其綁定到reference-to-nonconst。

這也沒有意義。 這就像說int a; &a = 12; int a; &a = 12; 顯然你無法改變變量a的地址。

相反,你想要這個:

int a;
int * p = &a;
mutate_me(p);    // declared as mutate_me(int * &);

如果函數不需要突變指針,由常量-引用或值要么通過。

在寫下類似的東西時考慮一下情況

void foo(bar*& ptr) {
  ptr = new bar;
}

bar b;
foo(&b);

非正式地,通過引用期望參數的方法期望它被傳遞到可以合法地放置在賦值語句的左側的東西(有時稱為“左值”)。

int main()
{
    my_class a;
    my_class b(&a);                   // Not legal: &a = 0; would be illegal because you can't change an address of a variable.

    // ---
    my_class a;
    my_class* a_ptr = &a;
    my_class b(a_ptr);                    // Legal: You've declared a_ptr on the stack and its value (what it points to) can be changed. The address of a_ptr would not be changeable though.

    // ---
    my_class* a = new my_class;
    my_class* b = new my_class(a);    // Legal: Again, this is on the stack and `a` could point to something else, but its own address won't be changed.
}

在這種情況下,值得指出的是,在大多數情況下,按值傳遞指針是便宜的並且可以工作。 如果你真的需要指針可修改(通過引用傳遞),那么你需要傳遞一個左值。

另一種選擇是使引用為const 然后我相信你可以通過rvalues就好了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM