kembedded
kembedded

Reputation: 515

Why doesn't compiler raise an error when copy assignment function doesn't return anything?

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.

#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

Upvotes: 0

Views: 78

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254431

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.

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.

Upvotes: 5

Related Questions