Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there sense in using const std::string& arguments in C++17?

Tags:

c++

c++17

By getting string_view in C++17 we got cheap method of passing both std::string and char* to functions that do not take ownership of the string and avoid making temporary copies. By using std::string passed by value and std::move we get explicit and fast passing of string ownership for both r-value and l-value references.

My question is: is there any benefit in using const std::string& as any function parameter in new C++ standard?

like image 551
bartop Avatar asked Sep 16 '19 07:09

bartop


People also ask

What is const std::string?

The data type const string& literally means “a reference to a string object whose contents will not be changed.” There are three ways to pass things around (into and out of functions) in C++: 1. Pass by value - a copy of the original object is created and passed.

Should I use string_view?

string_view is useful when you want to avoid unnecessary copies. String_views are less memory-intensive to construct and copy. The creation of string_view from literals does not require a dynamic allocation.

Why do we use std::string?

std::string class in C++ C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.

Is std::string movable?

Yes, std::string (since C++11) is able to be moved i.e. it supports move semantics.


1 Answers

Yes.

The problem with std::string_view is that it doesn't remember if it points to a null-terminated string or not.

If you're writing a wrapper for a C api that uses null-terminated strings, you would have to constantly copy your std::string_views into std::strings to make sure you have null-terminators.

like image 107
HolyBlackCat Avatar answered Sep 22 '22 13:09

HolyBlackCat