6

I'm trying to concatenate string_views in a constexpr. The following is a simplified version of my code:

#include <iostream>
#include <string_view>

using namespace std::string_view_literals;

// concatenate two string_views by copying their bytes
// into a newly created buffer
constexpr const std::string_view operator+
    (const std::string_view& sv1, const std::string_view& sv2)
{
    char buffer[sv1.size()+sv2.size()] = {0};
    for(size_t i = 0; i < sv1.size(); i++)
        buffer[i] = sv1[i];
    for(size_t i = sv1.size(); i < sv1.size()+sv2.size(); i++)
        buffer[i] = sv2[i-sv1.size()];
    return std::string_view(buffer, sv1.size()+sv2.size());
}

int main()
{
    const std::string_view sv1("test1;");
    const std::string_view sv2("test2;");
    std::cout << sv1 << "|" << sv2 << ": " << (sv1+sv2+sv1) << std::endl;
    std::cout << "test1;"sv << "|" << "test2;"sv << ": " <<
        ("test1;"sv+"test2;"sv) << std::endl;
    return 0;
}

However this code does not produce the result I expected. Instead of printing test1;test2;test1 and test1;test2; it prints out correct characters mixed with random characters as if I'm accessing uninitialized memory.

test1;|test2;: F��<��itest;
test1;|test2;: est1;te`�i

However if I remove the constexpr specifier and replace the string_views with strings the above code prints the expected output.

test1;|test2;: test1;test2;test1;
test1;|test2;: test1;test2;

Either I'm missing some obvious mistake in my code or there is something about constexpr that I don't understand (yet). Is it the way I'm creating the buffer for the new string_view? What else could I do? Or is what I'm trying to do impossible? Maybe there is someone who can shed light to this for me.

11
  • You cannot concatenate references. And string_view is a reference type. Commented Nov 29, 2017 at 16:09
  • 1
    char buffer[sv1.size()+sv2.size()] is not standard C++. VLA is an extension. (function arguments are not constexpr). Commented Nov 29, 2017 at 16:18
  • 1
    @Jarod42, actually, std::string_view::size() being constexpr means that as long as the function is called with constexpr arguments, this is actually fine. That should be enforced with a local constexpr variable,of course, but I believe his specific example is actually ok. Commented Nov 29, 2017 at 16:42
  • @Frank: sv1 is not constexpr (and we don't have way to express that currently). so sv1.size() is not constexpr. Commented Nov 29, 2017 at 16:45
  • 1
    You got warning with correct flag: Demo. See also disable-variable-length-automatic-arrays-in-gcc Commented Nov 29, 2017 at 16:58

3 Answers 3

2

Your task is fundamentally impossible, since string_view, by definition, needs to have continuous non-owning storage from start to finish. So it'll be impossible to manage the lifetime of the data.

You need to create some kind of concatenated_string<> custom range as your return type if you want to do something like this.

As to the specific reason your code is yielding weird results, it's simply because buffer does not exist anymore when the function exits.

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

1 Comment

Ah it seems possible ... here is the design ' template<char... str0, char... str1> inline constexpr string<str0..., str1...> operator+(string<str0...>, string<str1...>) { return {}; }' just please implement the string<char ...> and implement transforming from std::string_view into it :)
2

In return std::string_view(buffer, sv1.size()+sv2.size()); the returned string_view views the buffer which goes out of scope, so you essentially have a dangling reference.

Comments

2

To concat string_view, create storage for new string_view.

To concat string_view and results in constexpr, create static storage for new string_view.

In C++20, constexpr staitc storage can be created easily.

Before C++20, you have to use template specialization with Parameter pack to assign each element, which is possible but very complicated.

There is a example in C++20:

template<const std::string_view &sv1, const std::string_view &sv2>
struct StringViewCat{
    static constexpr auto get_arr()
    {
        std::array<char, sv1.size() + sv2.size()> arr;
        for(auto i = 0; i < sv1.size(); ++i)
            arr[i] = sv1[i];
        for(auto i = 0; i < sv2.size(); ++i)
            arr[i+sv1.size()] = sv2[i];
        
        return arr;
    }
    constexpr static std::array<char, sv1.size() + sv2.size()> arr = get_arr();
    constexpr static std::string_view data{arr.data(), arr.size()};
};

Usage:

    static constexpr auto a = "a"sv;
    static constexpr auto b = "b"sv;
    constexpr auto c = StringViewCat<a, b>::data;

2 Comments

Thanks, this actually works :-) You could also add something like template<const std::string_view &sv1, const std::string_view &sv2> constexpr std::string_view string_view_cat = StringViewCat<sv1, sv2>::data; to simplify the user code: constexpr auto c = string_view_cat<a, b>;
it is very useful, something along those lines should be added to the standard. It should also be possible to generalize the concept to any number of concatenated string_views with the fold expressions

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.