簡體   English   中英

從T **重構到vec時返回對臨時錯誤的引用 <vec<T> &gt;

[英]Returning reference to temporary error when remodeling from T ** to vec<vec<T>>

我在operator []代理類中遇到了一個錯誤。 它正在檢查索引是否在范圍內,並且當我用T** values.實現我的類模板時工作正常T** values.

但是我感覺就像將整個實現更改為std::vector<std::vector<T>> 一切都很好,期望operator[]

矩陣類運算符

//***************************************************************************
template <typename T>
X_Proxy<T> Matrix<T>::operator [](const size_t& j)
{
    if(j >= y)
        ERROR_MSG(Y_OUT_RANGE);
    return X_Proxy<T>(inner[j], x);
}

//***************************************************************************
template <typename T>
const X_Proxy<T> Matrix<T>::operator [](const size_t& j) const
{
    if(j >= y)
        ERROR_MSG(Y_OUT_RANGE);
    return X_Proxy<T>(inner[j], x);
}
//***************************************************************************

代理類模板定義:

template <typename T>
struct X_Proxy
{
    X_Proxy(std::vector<T> PTR, const size_t X) : x_ptr(PTR), x(X) {}
    T& operator [] (size_t pos);
    const T& operator [] (size_t pos) const;
    std::vector<T>& x_ptr;
    const size_t& x;
};

代理類運算符:

//***************************************************************************
template <typename T>
T& X_Proxy<T>::operator [] (size_t pos)
{
    if (pos > x-1)
        Matrix<T>::ERROR_MSG(Matrix<T>::X_OUT_RANGE);
    return x_ptr[pos];
}
//***************************************************************************
template <typename T>
const T& X_Proxy<T>::operator [] (size_t pos) const
{
    if (pos > x-1)
        Matrix<T>::ERROR_MSG(Matrix<T>::X_OUT_RANGE);
    return x_ptr[pos];  // <--- the error line
}

//***************************************************************************

矩陣誤差函數:

template <typename T>
void Matrix<T>::ERROR_MSG(const int& MSG)
{
    std::cerr << info[MSG] << std::endl;
    exit(MSG);
}

編譯錯誤:

..\matrix.h:47: error: returning reference to temporary [-Wreturn-local-addr]
         return x_ptr[pos];
                         ^

我們可愛的模板庫可能會出什么問題?

您的X_Proxy構造函數正在存儲對臨時文件的引用:

X_Proxy(std::vector<T> PTR, const size_t X) : x_ptr(PTR), x(X) {}

在這里, PTR是本地臨時x_ptr ,而x_ptr是左值引用:

std::vector<T>& x_ptr;

這不是標准的C ++,因此甚至不應該編譯。 但是您的編譯器允許這樣做,給您留下了麻煩的參考。

也許您想存儲對有效向量的引用:

X_Proxy(std::vector<T>& PTR, const size_t X) : x_ptr(PTR), x(X) {}
                      ^

只要由PTR引用的向量超過X_Proxy實例, X_ProxyX_Proxy

暫無
暫無

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

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