Is RVO (Return Value Optimization) applicable for all objects?

前端 未结 5 1810
小鲜肉
小鲜肉 2020-11-29 01:31

Is RVO (Return Value Optimization) guaranteed or applicable for all objects and situations in C++ compilers (specially GCC)?

If answer is \"no\", what are the condit

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 01:52

    Move semantics (new feature of C++11) is a solution to your problem, which allows you to use Type(Type &&r); (the move constructor) explicitly, instead of Type(const Type &r) (the copy constructor).

    For example:

    class String {
      public:    
        char *buffer;
    
        String(const char *s) { 
          int n = strlen(s) + 1;
          buffer = new char[n];
          memcpy(buffer, s, n);
        }
    
        ~String() { delete [] buffer; }
        
        String(const String &r) { 
          // traditional copy ...
        }
    
        String(String &&r) {
          buffer = r.buffer; // O(1), No copying, saves time.
          r.buffer = 0;
        }
    };
    
    String hello(bool world) {
      if (world) {
        return String("Hello, world.");
      } else {
        return String("Hello.");
      }
    }
    
    int main() {
      String foo = hello();
      std::cout <

    And this will not trigger the copy constructor.

提交回复
热议问题