簡體   English   中英

如何在c ++中解釋“const int * const&variable”

[英]How “const int *const & variable” is interpreted in c++

當一個將兩個變量別名為

int a;
const int &b = a;

這兩個變量實際上是相同的,因此應用於變量a任何更改也會應用於變量b 但是,當使用指針完成相同的技巧時,它似乎無法以相同的方式工作,如以下程序所示:

#include <iostream>
int main(void) {

    int *a = (int*) 0x1;
    const int *const &b = a;// Now b should be an alias to a.
    a = (int*) 0x2;// This should change b to 0x2.
    std::cout << b << "\n";// Outputs 0x1 instead of the expected value of 0x2.

    return 0;
}

現在變量a似乎不是變量b的別名,但為什么呢?

const int *const &是到參考const指針const int (盡量由右至左讀它。)注意,指針的類型是const int * ,但不能int * (即類型a )。 引用不能直接綁定到不同的類型。 對於const int *const &b = a; 將構造臨時* (具有類型const int * ,從a復制),然后綁定到引用; 臨時與a無關,因此對b任何修改都不會影響a

注意區別。 在第一個樣本中, const是在int ; 在第二個示例中, const不僅限定了指針本身,還限定了指針,它使兩個指針成為不同的類型( int *const int * )。 如果你想在它上限定const (這對於你的實驗來說似乎是不必要的)你應該只在指針本身上限定它,即int * const &


* 臨時的生命周期延長到參考b的生命周期。

const int * const & b表示對const int的const指針的引用。 你想要的是int * const & b

使用這個方便的工具來破譯復雜的聲明。 https://cdecl.org/

暫無
暫無

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

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