简体   繁体   中英

How is a std::string parameter passed from a raw character array literal?

First of all, I do not really know how I put title on this question.. So we have this code:

class Example5 {
    string* ptr;
  public:
    Example5 (const string& str) : ptr(new string(str)) {}
    ~Example5 () {delete ptr;}
    // access content:
    const string& content() const {return *ptr;}
};

int main () {
  Example5 foo ("Example");

  cout << "bar's content: " << foo.content() << '\n';
  return 0;
}

So the constructor of the class Example5 is initializing the pointer ptr to be a pointer to str , right?

Is it an optimal way to have const string& str as the parameter instead of string str ? I mean since str is used as something to be pointed to by ptr , why is the value of the argument not just get copied instead of making a reference to an unnamed entity/the string literal? Is this optimal?

So the constructor of the class Example5 is initializing the pointer ptr to be a pointer to str , right?

No! It creates a new std::string instance and copies what's passed in the parameter.

why is the value of the argument not just get copied instead of making a reference to an unnamed entity/the string literal?

Good question, yes.

Is this optimal?

No.


The usual way would be simply not to use a pointer at all:

class Example5 {
    string s;
  public:
    Example5 (const string& str) : s(str) {}
    // access content:
    const string& content() const {return s;}
};

To avoid taking a copy (if that's actually your concern) you could alternatively write

class Example5 {
    string s;
  public:
    Example5 (string str) : s(std::move(str)) {}
    // access content:
    const string& content() const {return s;}
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM