简体   繁体   English

const_iterator和模板,编译错误

[英]const_iterator and template, compilation error

I can't understand why the following code is not working, any idea ? 我不明白为什么下面的代码不起作用,知道吗?

template <class T>
class Matrice
{
public:
...
    typedef typename std::vector<T>::const_iterator const_iterator;
    const_iterator& cend ( )
    {
        return valeurs.cend ( );
    }
...
private:
...
}

here's the complilator's complaint : 这是投诉人的投诉:

/Users/Aleks/Documents/DS OO/DS OO/Matrice.h:70:16: Non-const lvalue reference to type 'const_iterator' (aka '__wrap_iter') cannot bind to a temporary of type 'const_iterator' (aka '__wrap_iter') / Users / Aleks / Documents / DS OO / DS OO / Matrice.h:70:16:对“ const_iterator”类型(即“ __wrap_iter”)的非常量左值引用无法绑定到“ const_iterator”类型(即“ __wrap_iter“)

valeurs.cend ( cppreference ) returns an instance to a const_iterator (that is, it's declared as const_iterator valeurs.cend() ). valeurs.cendcppreference )将实例返回到const_iterator (即,它被声明为const_iterator valeurs.cend() )。

The compiler needs to create a temporary object (memory area) to store the value returned by valeurs.cend() . 编译器需要创建一个临时对象 (内存区域)来存储valeurs.cend()返回的值。 This code fails to compile because you cannot take the reference of a temporary as the latter won't outlive the function call. 该代码无法编译,因为您不能引用一个临时变量,因为后者不会超出函数调用的寿命。

You'd usually return an iterator by value: 您通常会按值返回一个迭代器:

typedef typename std::vector<T>::const_iterator const_iterator;
const_iterator cend ( )
{
    return valeurs.cend ( );
}

This will make sure the value returned by valeurs.cend() is copied (or moved, in C++11, I believe) to its the destination object (if you're assigning the returned value to a variable of type const_iterator ) or in another temporary wherever Matrice<T>::cend() is called. 这将确保将valeurs.cend()返回的值复制(或移动,在C ++ 11中,我相信)到其目标对象(如果您将返回的值分配给const_iterator类型的变量)或在另一个调用Matrice<T>::cend()的地方。 See the link to MSDN's explanation for details. 有关详细信息,请参见MSDN解释的链接。

hmjd is right, you need just const_iterator, not a reference. hmjd是正确的,您只需要const_iterator,而不是引用。 The reason you can't use a reference is that valeurs.cend () is a temporary value on the stack, the reference (if you could use it) wouldn't be valid as soon as the function returns. 您不能使用引用的原因是valeurs.cend()是堆栈上的临时值,该引用(如果可以使用)将在函数返回后立即失效。

As others have said, the following line: 正如其他人所说,以下行:

const_iterator& cend ( )

Needs to be either: 需要为:

const const_iterator& cend ( )

Or: 要么:

const_iterator cend ( )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM