본문 바로가기

프로그래밍/C++

C++17 string_view


https://skebanga.github.io/string-view/

#include <iostream>
#include <experimental/string_view>

void* operator new(std::size_t n)
{
    std::cout << "[allocating " << n << " bytes]\n";
    return malloc(n);
}

bool compare(std::experimental::string_view s1, std::experimental::string_view s2)
{
    if (s1 == s2)
        return true;
    std::cout << '\"' << s1 << "\" does not match \"" << s2 << "\"\n";
    return false;
}

int main()
{
    std::string str = "this is my input string";

    compare(str, "this is the first test string");
    compare(str, "this is the second test string");
    compare(str, "this is the third test string");

    return 0;
}
[allocating 24 bytes]
"this is my input string" does not match "this is the first test string"
"this is my input string" does not match "this is the second test string"
"this is my input string" does not match "this is the third test string"

C++17에 추가되는  string_view 를 쓰는 이유는 간단하다.

literals의 경우, 동적으로 메모리를 할당하지 않기 때문이다.

사용할때 네임스페이스 experimental 를 추가해 줘야 한다.