I intend to perform in-place modification of std::string with the help of a modifier function. In this regard, I looked up on internet and found that pass by pointer method is not recommended. I have few queries in this regard.

  • If I pass a std::string to the function as pass by value, would it be considered as in-place modification if I don't create any new std::string in modifier function?
  • What is the standard and efficient ethod to modify std::string in place?
  • How to change the end of std::string? One way that I could think of is to assign '\0' to all the trailing characters of the string but it would be inefficient to do so if length of string is large.

Why not pass by reference?

The std::string class comes with a number of class functions for modifying the string. Using those is the standard way to modify the string.

How to change the end of std::string?

You mean remove the last part of the string? Use erase for that.

One way that I could think of is to assign '\0' to all the trailing characters of the string but it would be inefficient to do so if length of string is large.

std::strings are not 0-terminated. Setting their characters to \0 does not make them shorter.

If I pass a std::string to the function as pass by value, would it be considered as in-place modification if I don't create any new std::string in modifier function?

An algorithm is called "in-place" (or "in-situ") when it works on input using constant, small extra storage space. So yes, it would.

What is the standard and efficient method to modify std::string in place?

The standard would be to use its member functions: erase, insert, replace, swap, append, and so on. I wouldn't really know another way of dealing with std::string. As far as efficiency goes, you can't really say much about it I suppose. You use the member functions in an abstract way, you don't know how they work, you only know what they do.

How to change the end of std::string? One way that I could think of is to assign '\0' to all the trailing characters of the string but it would be inefficient to do so if length of string is large.

What exactly would your modification be? As mentioned before \0 wouldn't work for std::string. But if you had a C-string I don't see why you'd have to insert more than 1.

size_t size() const; This is what I found as function prototype of std::string.size(). Is it so that const function can be called by either const or non-const object while non-const function can't be called by const object?

a const function can be called by a non const function. a const function can only call other const functions. the same thing applies to objects as well.

This question has already been answered. Start a new discussion instead.