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

后端 未结 9 2495
隐瞒了意图╮
隐瞒了意图╮ 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

    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.

提交回复
热议问题