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

后端 未结 9 2625
隐瞒了意图╮
隐瞒了意图╮ 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: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. :-)

提交回复
热议问题