Question: assigning to a function that returns a reference

Question

assigning to a function that returns a reference

Answers 1
Added at 2016-12-16 10:12
Tags
Question

I am currently refactoring some code and wondering whether the following (i.e. assigning to a function that returns a reference) is actually bad style (at least it looks weird):

#include <iostream>

class A{
    public :
        double & operator()() {
            return this->x;
        };

        double   operator()() const{
            return this->x;
        };

    protected :
        double x = 0.0;
};

int main(){
    A a;
    a() = 4.0;
    std::cout<<a()<<std::endl;  //prints 4.0 as expected.
};

The background behind this is that I have some code that works in parallel and using something like:

A.d

is simply not an option, whereas:

A()

would work, as I can leave the memory selection to a function.

(I know coding style is a somewhat subjective issue, but I am a scientist and not a software engineer and good practice feedback is appreciated)

Answers to

assigning to a function that returns a reference

nr: #1 dodano: 2016-12-16 10:12
a() = 4.0;

This is not really bad practice. You're doing something equivalent each time you dereference a container:

a[i] = 4.0;

Here operator[] is returning a reference, and you're assigning it.

operator() may not be the more readable choice here. Depending on the context of your code, something like operator* may be a better choice, but that's a matter of opinion ;)

#include <iostream>

class A{
    public :
        double & operator*() {
            return this->x;
        }

        double   operator*() const{
            return this->x;
        }

    protected :
        double x = 0.0;
};

int main(){
    A a;
    *a = 4.0;
    std::cout<<(*a)<<std::endl;  //prints 4.0 as expected.
};

double & operator()() {
    return this->x;
};

Note that you don't need trailing ; when defining a function. Do:

class A{
    // ...
    double & operator()() {
        return this->x;
    }
    // ...
};

Or:

class A{
    // ...
    double & operator()();
    // ...
};

double & A::operator()() {
    return this->x;
}
Source Show
◀ Wstecz