了解模板中的 & 运算符

Understanding the & operator in templates

本文关键字:运算符 了解      更新时间:2023-10-16

所以我目前正在阅读sams template <typename objectType> objectType & GetMax (const objectType & value1, const objectType & value2) { if (value1 > value2) return value1; else return value2; };

另一个例子:

Template <typename T>  
class myTemplateClass  
{  
public:   
    void SetVariable (T& newValue) {m_Value = newValue; };
    T& GetValue() {return m_Value;};
private:   
    T m_Value;  
};

请帮助我理解为什么&,我知道得到数据类型的地址,在这里!这绝对不会让学习STL变得更容易..........谢谢!div =)

这不是操作符,也与模板没有(直接)关系。

它是一个类型修饰符,创建(或指示、表示或形成)一个引用,就像*创建一个指针一样。

很多时候,这是一种优化,而不是必要的。两个三种必要的情况:

  • 在复制构造函数中,需要避免无限递归:

    class X
    {
         //X(X);
         // pass by value, the formal parameter is a copy of the actual parameter
         // the copy constructor must be called to make the copy
         X(const X&); // pass by reference, ok, no copy constructor call necessary
    };
    

    Const引用通常避免了复制大对象,这是一个有用的优化,没有意外的行为。

  • 当函数的返回类型,特别是operator[]重载,必须出现在表达式的左侧时:

    class Container
    {
         //Element operator[](int index);
         // problematic because c[i] is a temporary
         // so c[i] = 5; doesn't actually modify the collection, like it would with an array
         Element& operator[](int index); // correct
    

    };

    与此类似,对于改变左操作数的操作符,如复合赋值和流插入,必须使用非const引用形参。

任何其他情况(例如输出参数)都可以(而且我认为应该)用指针处理,因为一个函数调用看起来像按值传递,但改变了它的参数,违反了最小意外原则。完美的例子:auto_ptr<int> a = new int(5); f(a); /* is a still valid !?! */

这就引出了第三种情况(因为有人在操作符之外使用了非const引用而产生的):

  • 在模板中,当实际类型可能是auto_ptrunique_ptr时,需要引用来避免推断破坏原始类型的类型:

    auto_ptr<int> a = new int(5);
    //template<typename T>
    //void dump_target( T handle ) { cout << *item; }
    // bad: dump_target(a); destroys *a
    template<typename T>
    void dump_target( const T& handle ) { cout << *item; } // correct