When is it not a good idea to pass by reference?

后端 未结 9 2443
隐瞒了意图╮
隐瞒了意图╮ 2021-02-10 10:31

This is a memory allocation issue that I\'ve never really understood.

void unleashMonkeyFish()  
{  
    MonkeyFish * monkey_fish = new MonkeyFish();
    std::string          


        
相关标签:
9条回答
  • 2021-02-10 10:33

    One way to do this is to have your string

    std::string name;
    

    As the data-member of your object. And then, in the unleashMonkeyFish function create a string like you did, and pass it by reference like you showed

    void setName( const std::string & parameter_name ) {
        name = parameter_name;
    }
    

    It will do what you want - creating one copy to copy the string into your data-member. It's not like it has to re-allocate a new buffer internally if you assign another string. Probably, assigning a new string just copies a few bytes. std::string has the capability to reserve bytes. So you can call "name.reserve(25);" in your constructor and it will likely not reallocate if you assign something smaller. (i have done tests, and it looks like GCC always reallocates if you assign from another std::string, but not if you assign from a c-string. They say they have a copy-on-write string, which would explain that behavior).

    The string you create in the unleashMonkeyFish function will automatically release its allocated resources. That's the key feature of those objects - they manage their own stuff. Classes have a destructor that they use to free allocated resources once objects die, std::string has too. In my opinion, you should not worry about having that std::string local in the function. It will not do anything noticeable to your performance anyway most likely. Some std::string implementations (msvc++ afaik) have a small-buffer optimization: For up to some small limit, they keep characters in an embedded buffer instead of allocating from the heap.

    Edit:

    As it turns out, there is a better way to do this for classes that have an efficient swap implementation (constant time):

    void setName(std::string parameter_name) {
        name.swap(parameter_name);
    }
    

    The reason that this is better, is that now the caller knows that the argument is being copied. Return value optimization and similar optimizations can now be applied easily by the compiler. Consider this case, for example

    obj.setName("Mr. " + things.getName());
    

    If you had the setName take a reference, then the temporary created in the argument would be bound to that reference, and within setName it would be copied, and after it returns, the temporary would be destroyed - which was a throw-away product anyway. This is only suboptimal, because the temporary itself could have been used, instead of its copy. Having the parameter not a reference will make the caller see that the argument is being copied anyway, and make the optimizer's job much more easy - because it wouldn't have to inline the call to see that the argument is copied anyway.

    For further explanation, read the excellent article BoostCon09/Rvalue-References

    0 讨论(0)
  • 2021-02-10 10:33

    If you use the following method declaration:

    void setName( const std::string & parameter_name );
    

    then you would also use the member declaration:

    std::string name;
    

    and the assignment in the setName body:

    name = parameter_name;
    

    You cannot declare the name member as a reference because you must initialise a reference member in the object constructor (which means you couldn't set it in setName).

    Finally, your std::string implementation probably uses reference counted strings anyway, so no copy of the actual string data is being made in the assignment. If you're that concerned about performance, you had better be intimately familiar with the STL implementation you are using.

    0 讨论(0)
  • 2021-02-10 10:34

    You could make the string in unleashMonkeyFish static but I don't think that really helps anything (and could be quite bad depending on how this is implemented).

    I've moved "down" from higher-level languages (like C#, Java) and have hit this same issue recently. I assume that often the only choice is to copy the string.

    0 讨论(0)
  • 2021-02-10 10:37

    As a simple rule of thumb store your data as a copy within a class, and pass and return data by (const) reference, use reference counting pointers wherever possible.

    I'm not so concerned about copying a few 1000s bytes of string data, until such time that the profiler says it is a significant cost. OTOH I do care that the data structures that hold several 10s of MBs of data don't get copied.

    0 讨论(0)
  • 2021-02-10 10:37

    In your example code, yes, you are forced to copy the string at least once. The cleanest solution is defining your object like this:

    class MonkeyFish {
    public:
      void setName( const std::string & parameter_name ) { name = parameter_name; }
    
    private:
      std::string name;
    };
    

    This will pass a reference to the local string, which is copied into a permanent string inside the object. Any solutions that involve zero copying are extremely fragile, because you would have to be careful that the string you pass stays alive until after the object is deleted. Better not go there unless it's absolutely necessary, and string copies aren't THAT expensive -- worry about that only when you have to. :-)

    0 讨论(0)
  • 2021-02-10 10:43

    This is precisely the problem that reference counting is meant to solve. You could use the Boost shared_ptr<> to reference the string object in a way such that it lives at least as long as every pointer at it.

    Personally I never trust it, though, preferring to be explicit about the allocation and lifespan of all my objects. litb's solution is preferable.

    0 讨论(0)
提交回复
热议问题