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

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

提交回复
热议问题