mercredi 31 août 2022

Shall I try to use const T & as much as possible?

I am learning books <Effective C++>, i think use const reference is a good practice. because it can avoid unnecessary copy.

so, even in initialize a object, i use const T & t = T();

here is the code:

#include <string>
#include <iostream>
#include <vector>

using namespace std;

template <class T>
inline std::vector<std::string> Split(const std::string &str, const T &delim, const bool trim_empty = false) {
  if (str.empty()) return {}; 
  size_t pos, last_pos = 0, len;
  std::vector<std::string> tokens;
  std::string delim_s = ""; 
  delim_s += delim;
  while(true) {
    pos = str.find(delim_s, last_pos);
    if (pos == std::string::npos) pos = str.size();
    len = pos-last_pos;
    if ( !trim_empty || len != 0) tokens.push_back(str.substr(last_pos, len));
    if (pos == str.size()) break; 
    else last_pos = pos + delim_s.size();
  }   
  return tokens;
}

int main() {
  const std::string& str = "myname@is@haha@";  // compare with std::string = "", will this be better(in speed and memory)?
  const std::string& s = Split(str, "@").front();  // this crashed
  // std::string s = Split(str, "@").front();  // this ok
  cout << "result is " << s << endl;
}

As you see above, this code is used to split a string into vector<std::string>,

in main function:

I have two method to get the first element of the splited results.

1.const std::string& s = Split(str, "@").front();

2.std::string s = Split(str, "@").front();

in my test, option 1 will crashed, option2 is ok.

could you talk some difference of these?

and is it necessary to do this (const std::string& s = "asd";)?

comparing to std::string s = "asd", what is the advantages and disadvantages of them?

Aucun commentaire:

Enregistrer un commentaire