簡體   English   中英

使用`std :: vector`不會在顯式構造函數中持久分配`const reference`成員。

[英]Assignment of `const reference` member in explicit Constructor is not persistent using `std::vector`

在Eplace中使用Dangerous隱式轉換的源代碼,我檢測到以下行為:

struct Foo
{
public:
    explicit Foo(const int& i) : i(i) { 
        cout << "explicit int ctor called" << endl; }
    explicit Foo(const double& x) : i(i) { 
        cout << " explicit double ctor called // i : " << i << endl; }
    Foo(int&&) = delete; 
    Foo(double&&) = delete; 

    void foo() const { 
        cout << i << endl; }  
private:
    const int& i;
};

void bar(const double& d) {
    cout << "---------- create object vector ------------" << endl; 
    std::vector<Foo> fv;
    fv.emplace_back(d);
    fv[0].foo(); 

    cout << "---------- create object default ------------" << endl; 
    Foo f(d); 
    f.foo(); 
}

int main(){
    bar(5.0); 
    return 0; 
}

印刷品:

---------- create object vector ------------
explicit double ctor called // i : 5
0
---------- create object default ------------
explicit double ctor called // i : 5
5

因此,在兩種情況下,引用成員都會在對象創建期間正確初始化,由輸出i = 1 但是在兩個對象上調用foo()函數后,它們將產生不同的結果。 從向量中檢索最近放置的Object會打印0甚至認為它應該打印1 另一個對象執行正確。

問題為什么將const引用成員的值放在STL容器中時不持久? (我對“僅僅不要將(const)引用用作類成員)之類的建議不感興趣。”

在這行上:

explicit Foo(const double& x) : i(i) {

成員引用i自身進行了初始化,從而導致未定義的行為

暫無
暫無

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

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