PrevUpHomeNext

std::string_view avoid unnecessary allocation


std::string_view avoid unnecessary memory allocation - Posted on Sep 11, 2024 - See https://en.cppreference.com/w/cpp/string/basic_string_view - Logs Home - d0033

c++

Using std::string_view to avoid unnecessary memory allocation

std::string_view

#include <string_view>
#include <vector>
#include <string>

namespace str
{

class str_dup
{
public:
	void mp(const std::string &) {}
	void np(const std::string_view) {}
};

}

int main()
{
	const char * cpp_str = "c++ string";
	const std::string std_str = "std::string";
	const std::vector<char> v_str{':', ':', 'v'};
	str::str_dup dup;
	dup.mp(cpp_str);	// temp copy
	dup.mp("c++ str");	// temp copy
	dup.mp(std_str);	// no copy
	dup.mp({v_str.begin(), v_str.end()});	// temp copy

	dup.np(cpp_str);	// no copy
	dup.np("c++ str");	// no copy
	dup.np(std_str);	// no copy
	dup.np({v_str.begin(), v_str.end()});	// no copy
}

std::string_view constructors accept:

std::string constructor and std::string_view

std::string_view sv = "c++ string";
std::string s1{sv};	// OK
std::string s2 = sv;	// error
#include <string_view>
#include <string>
#include <iostream>

int main()
{
	std::string str = "c++ string";
	std::string_view v;
	v = str;
	str = v;
	//std::string v3 = v;	// error
	std::string v4{v};	// OK
	std::string s2 = v.data();	// OK
	v = s2.data();
	std::cout << "v=>" << v << std::endl;
	std::cout << "s2=>" << s2 << std::endl;
}

See Also

std::views::zip


PrevUpHomeNext

E

U