최대 1 분 소요

1. std::string_view

C++ 17부터 추가된 string을 복사없이 사용할 수 있게 하는 문법

#include <iostream>
using namespace std;

void GetString(const string& input)
{
	cout << input << endl;
}

void GetStringStringView(const std::string_view input)
{
	cout << input << endl;
}

int main()
{
	string strInput("Hello world");
	const char* charPtrInput = "Hello world";
	char charArrayInput[] = "Hello world";

	GetString(strInput);		//복사생성자 호출 안함
	GetString(charPtrInput);	//복사생성자 호출!
	GetString(charArrayInput);	//복사생성자 호출!

	GetStringStringView(strInput);			//복사생성자 호출 안함
	GetStringStringView(charPtrInput);		//복사생성자 호출 안함
	GetStringStringView(charArrayInput);	//복사생성자 호출 안함

	return 0;
}

std::string_view는 문자열을 복사없이 그대로 참조하는 성격을 가지고 있다
또한 C++에서는 std::string 뿐만이 아니라 위의 예시처럼 여러 type의 문자열이 있다

즉, 여러 타입의 문자열들을 포괄적으로 하나의 자료형으로 복사 없이 받아주기 위해서 사용한다고 보면 됨

참조형이기 때문에 주의할 점

원본 메모리를 참조하는 참조형이 기본적이기 때문에 원본 문자열의 메모리가 소거될 경우 문제가 생긴다

댓글남기기