0

my question is how to write function which creates object.

For example:

class MyVector {
public:
  std::vector<int> vec_;
  MyVector() = default;
  MyVector(const MyVector&) = default;
  MyVector& operator=(const MyVector&) = default;
  MyVector(MyVector&&) = default;
  MyVector& operator=(MyVector&&) = default;
  void add(int value) {
    vec_.push_back(value);
  }
};

// Ver. 1 of functions:

std::string to_string(const MyVector& vec) {
    std::string vecStr;
    for(const auto value: vec.vec_) {
        vecStr += std::to_string(value);
    }
    return vecStr;
}

MyVector create_vector() {
    MyVector vec;
    for(int i = 0; i < 1000; ++i) {
        cout << i << endl;
        vec.add(i);
    }
    return vec;
}

// Ver. 2 of functions:

std::string toString(const MyVector& vec) {
    std::string vecStr;
    for(const auto value: vec.vec_) {
        vecStr += std::to_string(value);
    }
    return std::move(vecStr);
}

MyVector createVector() {
    MyVector vec;
    for(int i = 0; i < 1000; ++i) {
        vec.add(i);
    }
    return std::move(vec);
}

main:

int main()
{
    MyVector vec1 = create_vector();
    MyVector vec2 = std::move(createVector());
    std::string vec1Str = to_string(vec1);
    std::string vec2Str = std::move(toString(vec2));
    std::cout << vec1Str << std::endl;
    std::cout << vec2Str << std::endl;

    return 0;
}

Which version of functions is preferred? Do Ver.1 always guarantee RVO even if the content of vector wont be a fundamental type?

  • 2
    ["C++11 has a special rule that allows returning automatic objects from functions without having to write `std::move`. In fact, you should never use std::move to move automatic objects out of functions, as this inhibits the "named return value optimization" (NRVO)"](https://stackoverflow.com/a/11540204/3484570). Not sure if it is good enough as a duplicate as the answer is hidden in a wall of text. – nwp Oct 18 '17 at 21:18
  • 2
    trust RVO. as of c++17 it's mandated. – Richard Hodges Oct 18 '17 at 21:30
  • @RichardHodges: Kind of, and kind of not at all, not in any way related to this question. Terms like "mandatory foo" that are fed as twitter-sized sound bites are dangerous when they're so easily misunderstood to be whatever the listener wants them to be. – Kerrek SB Oct 19 '17 at 02:16

0 Answers0