c++ - 从模板中通过引用返回

标签 c++ visual-studio-2013 return-value

从通过引用返回对象的模板函数返回 *thisthis 有什么区别? 这两个选项在 VS2013 中编译没有任何问题;

代码是这样的

template <typename T>
class MyClass
{

public:
    MyClass(){ }
    ~MyClass();

    MyClass& operator=(const MyClass&);

};

template <typename T>
MyClass<T>& MyClass<T>::operator=(const MyClass& s_from)
{

    //do some work
    return *this;
    //also works
    //return this
}

template <typename T>
MyClass<T>::~MyClass()
{

}

最佳答案

对于模板编译器只检查语法。当你实例化你的模板并尝试复制对象时,你会得到返回的编译错误:

 MyQueue<int> a;
 MyQueue<int> b;
 a = b; /// ops

或者您可以显式实例化您的模板(在这种情况下编译器生成所有成员并且您会看到所有错误)

template class MyQueue<int>;

所以 return *this 是从成员函数或运算符返回对象引用的唯一方法。

关于c++ - 从模板中通过引用返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37776859/

相关文章:

javascript - 每个 Javascript 函数都必须返回一个值吗?

c++ - 'auto ... arg' 的参数包形式在 lambda 中启用但在函数中没有启用?

c++ - 增加网关的负载能力

c++ - WriteFile重叠和fwrite等效

debugging - Visual Studio 2013 仅在调试菜单中显示附加

java - 如何通过从第一个类调用第二个类的方法来调用第三个类的方法

c++ - for std::queue remove all of element swap 和 pop 的时间差

c++ - 使用 Qt 线程和信号的缓冲区溢出

visual-studio - VS 2013 : Keyboard Shortcut to show the description of an error of mouseover

c - 函数什么时候应该返回什么?