I have run this code on VS2013 and Dev-C++ but when the copy assignment doesn't return anything while actually it should, the compiler doesn't raise any error, please help me to explain this.
我已经在VS2013和Dev-C ++上运行了这个代码但是当副本赋值没有返回任何实际应该的时候,编译器不会引发任何错误,请帮我解释一下。
#include <iostream>
using namespace std;
class sample
{
public:
sample()
{
cout << "X::X()" << endl;
}
sample(sample const &)
{
cout << "X::X( X const & )" << endl;
}
sample& operator=(sample const &)
{
cout << "X::operator=(X const &)" << endl;
}
};
sample f()
{
sample tmp;
return tmp;
}
int main()
{
int a;
sample x = f();
cin >> a;
return 0;
}
if I change to:
如果我改为:
sample x;
x = f();
VS2013 compiler will raise an error like: Error 1 error C4716: 'sample::operator=' : must return a value c:\users\xxx\desktop\test\test\main.cpp 33 1 Test
VS2013编译器会引发如下错误:错误1错误C4716:'sample :: operator =':必须返回值c:\ users \ xxx \ desktop \ test \ test \ main.cpp 33 1测试
1 个解决方案
#1
Strictly speaking, the compiler isn't required to diagnose this error, since a sufficiently twisted function could make that very difficult or even impossible. However, a decent compiler should be able to give a warning in a simple case like this; for example, GCC will if you specify -Wreturn-type
or -Wall
.
严格地说,编译器不需要诊断此错误,因为充分扭曲的功能可能使这非常困难甚至不可能。但是,一个像样的编译器应该能够在这样的简单情况下发出警告;例如,如果指定-Wreturn-type或-Wall,GCC将会出现。
From what you say, it sounds like Visual Studio, with whatever settings you're using, is only diagnosing this if the function is called. Your first snippet of code performs copy-initialisation (calling the copy constructor), but no assignment, so the assignment operator isn't called.
根据你的说法,它听起来像Visual Studio,无论你使用什么设置,只有在调用函数时才会诊断它。您的第一段代码执行复制初始化(调用复制构造函数),但没有赋值,因此不调用赋值运算符。
#1
Strictly speaking, the compiler isn't required to diagnose this error, since a sufficiently twisted function could make that very difficult or even impossible. However, a decent compiler should be able to give a warning in a simple case like this; for example, GCC will if you specify -Wreturn-type
or -Wall
.
严格地说,编译器不需要诊断此错误,因为充分扭曲的功能可能使这非常困难甚至不可能。但是,一个像样的编译器应该能够在这样的简单情况下发出警告;例如,如果指定-Wreturn-type或-Wall,GCC将会出现。
From what you say, it sounds like Visual Studio, with whatever settings you're using, is only diagnosing this if the function is called. Your first snippet of code performs copy-initialisation (calling the copy constructor), but no assignment, so the assignment operator isn't called.
根据你的说法,它听起来像Visual Studio,无论你使用什么设置,只有在调用函数时才会诊断它。您的第一段代码执行复制初始化(调用复制构造函数),但没有赋值,因此不调用赋值运算符。