1

According to https://en.cppreference.com/w/cpp/string/basic_string_view/basic_string_view, std::basic_string_view class has 7 overloaded ctors. I only care about 2 of them since right now I don't use the rest of them in my code.

These are the instances that I care about:

constexpr basic_string_view( const CharT* s, size_type count );
constexpr basic_string_view( const CharT* s );

I need to prevent the code from calling the second one (due to it potentially causing a buffer overflow for non-null terminated buffers).

I have something like below:

#include <iostream>
#include <sstream>
#include <string>
#include <array>

void func( const std::string_view str )
{
    if ( str.empty( ) )
    {
        return;
    }

    std::stringstream ss;

    if ( str.back( ) == '\0' )
    {
        ss << str.data( );
    }
    else
    {
        ss << std::string{ str };
    }
}

int main()
{
    std::array<char, 20> buffer { };
    std::cin.getline( buffer.data( ), 20 );

    const std::string_view sv { buffer.data( ), buffer.size( ) };

    func( sv ); // should be allowed
    func( { buffer.data( ), buffer.size( ) } ); // should be allowed
    func( buffer.data( ) ); // should NOT be allowed!
}

What is the correct way of doing this?

1 Answer 1

5

Add another overload taking const char* and mark it as delete (since C++11).

void func( const char* str ) = delete;

LIVE

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.