P
P
Ptax2016-06-24 05:53:13
Programming
Ptax, 2016-06-24 05:53:13

Why do programmers dislike returning const references in C++?

Looking through someone else's code, I noticed that almost no one, when writing getters, uses the return of a constant reference to a private class member. The strangest thing is that this applies not only to projects with a long history, but also relatively recent works. Indeed, in theory, returning a reference is a much less resource-intensive operation, especially if we are talking not about trivial objects, but about more or less complex structures.
How good do you think the following code is? If you think it's bad, please write why. Perhaps there are "pitfalls" invisible to me in this approach? Thank you.

#include <string>
#include <iostream>

class Foo{
public:
    Foo(const char* str)
        : m_value(str)
    {
    }

    const std::string& value() const{
        return m_value;
    }
private:
    std::string m_value;
};

int main(int argc, char** argv)
{
    if(argc < 1)
        return -1;

    Foo foo(argv[0]);

    auto&& bar = foo.value();
    std::cout << bar << std::endl;
    /* ... */

    return 0;
}

Answer the question

In order to leave comments, you need to log in

8 answer(s)
A
Anton Zhilin, 2016-06-24
@Anton3

If access is granted to the resources of the current object, then the return value is a reference (constancy depends, of course, on whether we forbid changing this data). Otherwise, the value.
Now let's imagine that there is a virtual class Window with a title method. How Window subclasses will store the title is an implementation detail, but they are contractually bound to cast it to a std::string in the getter. Hence the return by value: what type the value is stored in is an implementation detail.

R
Rou1997, 2016-06-24
@Rou1997

How good do you think the following code is? If you think it's bad, please write why.

It is not concise, this is a minus, but what are the pluses? If you are working with Qt, then you really need such constructs in your classes, because many Qt class methods accept exactly such parameters.

A
AtomKrieg, 2016-06-24
@AtomKrieg

After the object is destroyed, the reference is not valid and it doesn't matter if the reference is constant or not. In general, returning a reference is recommended only to a static member class. With the raw pointer the same situation.
Use weak_ptr (check for expired before each use) or shared_ptr to return from functions.

A
Adamos, 2016-06-24
@Adamos

In fact, life can be a bit more complicated. If you are passing by reference a member of a class that is itself a class and contains, for example, containers, then passing by reference will not fire the copy constructor. This will save time, but it will create a dependence of the further life of the code on what happens inside the class. That is, a potential rake, from which you will then be tortured to get rid of.
And programming, as you know, is primarily about managing complexity. Optimizations are much lower on the list.

M
Mercury13, 2016-06-24
@Mercury13

I think the only reason is that you don't have to look at the lifetime of an object.
If you need to save money, a smart pointer is embedded in the returned result. So work, for example, QStringand QDatabase.
But in some low-level vectors - quite a constant reference.
const T &QVector::at(int i) const

M
maaGames, 2016-06-24
@maaGames

I always return a constant reference for non-builtin types, if possible in the current context.

V
Vitaly, 2016-06-25
@vt4a2h

As for code... Code is code. If there is a real need to return by const reference and you cannot do without it, then return it. Of course, if it does not contradict the coding standards in your company, the API structure and all that. In any case, you must consider all the consequences and use cases in a real application. On a synthetic example, this cannot be seen. I would honestly prefer to see smart pointers, if the application is not quite the kind where you need to save on everything (and in order not to use smart pointers, you need justifications and good ones).
If a custom type supports implicit sharing (you can read about it in the Qt docs, they even have special classes that make life easier for those who want to create their own "copy on write" classes), then it can safely be returned by value. The same is true for smart pointers.

D
Daniil Demidko, 2016-06-25
@Daniro_San

The fact is that if you return a constant reference to the field, the field itself will not become constant from this. And all this is very well reduced to a regular pointer, after which you can change the value of the field.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question