简体   繁体   中英

assignment operator returning value type

I discovered by accident that an assignment operator returning not a reference, but a copy, serves as a workaround to enable storing objects with const members in an STL container.

class Test_class
{
public:
    int const whatever;

    explicit Test_class(int w) : whatever(w) {}

    // note the missing &
    Test_class operator=(Test_class const& rhs) {
        return Test_class(rhs.whatever);
    }
};

vector<Test_class> vec;
Test_class foo(42);
vec.push_back(foo);
assert(vec[0].whatever == 42);

This piece of code feels very strange, but gcc compiles it and it seems to work correctly.

So where are the pitfalls?

EDIT:

After the push_back() vec[0].whatever is, in fact, 42. Added an assert for illustration.

EDIT:

Thanks for the answers! Just for the fun of it, this version also runs just fine ;)

void operator=(Test_class const&) {
    throw 42;
}

Most of the accepted practice for operator overloading is not enforced by the standard or the compiler. It's just an expectation on the behaviour. You can check out some of it here: Operator overloading or here: http://en.cppreference.com/w/cpp/language/operators .

The pitfall here is that your operator= is not really an assignment operator. Consider this code:

Test_class a(15);
Test_class b(20);
a = b;

Normally you would expect a.whatever to be 20 after executing this code, however it's still 15.

C++03 requires vector elements to be both copy-constructible and copy-assignable and the compiler is free to choose what to use. In C++11 they only have to be copy-constructible (or move-constructible) so no assignment operator is required.

You don't actually assign anything here. You could even declare that assignment operator as const because it does nothing.

Test_class a(17);
Test_class b(33);

a = b; // nothing happens.  

The return value of operator= doesn't really matter, I for one typically declare it as void . It only matters if you do things like a = b = c; , which is not very common. And with your operator= this will compile, but again, does nothing at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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