What is the best way to return string in C++?

后端 未结 7 1075
刺人心
刺人心 2020-12-04 15:16

My question is simple: if I have some class Man and I want to define member function that returns man\'s name, which of the following two variants shall I prefer?

Fi

相关标签:
7条回答
  • 2020-12-04 15:37

    Rule #1 of optimization: Measure, optimize, measure. Or, as Knuth said, "premature optimization is the root of all evil".

    Unless you have a strong indication that simply returning std::string will significantly impact the performance of your software, just do so. If you can measure a significant impact, find the critical path, and optimize that. Don't make any funny, project-wide "optimizations" that likely result in little to no performance benefit, but negatively impact the readability, maintainability and robustness of your code.

    0 讨论(0)
  • 2020-12-04 15:39

    As we have move-semantics (in C++11), you can use this:

    string name();
    

    Even in C++03, this is almost good, as the compiler might optimize this (Search for Return Value Optimization).

    0 讨论(0)
  • 2020-12-04 15:40

    I think you should use first variant. Because this is simple getter method and such getter/setter approach is used everywhere.

    0 讨论(0)
  • 2020-12-04 15:50

    It's a good question and the fact that you're asking it shows that you're paying attention to your code. However, the good news is that in this particular case, there's an easy way out.

    The first, clean method is the correct way of doing it. The compiler will eliminate unnecessary copies, in most cases (usually where it makes sense).

    EDIT (6/25/2016)

    Unfortunately it seems that David Abaraham's site has been offline for a few years now and that article has been lost to the ethers (no archive.org copy available). I have taken the liberty of uploading my local copy as a PDF for archival purposes, and it can be found here.

    0 讨论(0)
  • 2020-12-04 15:53

    Since you want to create a getter for a field of your class, maybe you should go like that: inline const std::string& name() const { return this->name; }

    Since the name is returned as a const reference, it won't be modified outside the class, also no copy will be created by returning the name.

    After that, if you want to manipulate the name you will have to do a copy.

    0 讨论(0)
  • 2020-12-04 15:53

    I would go with the first. Return value optimization and C++11 will remove any copying overhead.

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