Is this temporary std::string expression acceptable?

87 Views Asked by At

I realize this isn't the most efficient thing to do, but is it acceptable C++ by most to create temporary std::string objects for concatenation, like here in line 4?

constexpr const char* const a = "This is ";
constexpr const char* const b = "a test.";

std::string s2 = std::string(a) + std::string(b);
std::cout << "*** " << s2 << std::endl;

I have to update some code in many, many places that previously used std::string concatenation to now use these constexpr character string constants, and it seems easier to just drop in some std::string(...) constructors to update the code rapidly.

This works in Visual C++ as I have it listed, and seems to compile in a gcc version that supports C++14 (need to test it yet).

1

There are 1 best solutions below

0
Benjamin Buch On

It is a valid but inefficient and slightly unattractive solution. Note that it is sufficient to cast the first operand into a std::string. This is slightly more efficient.

Starting with C++20 std::format() is the best way to do this.

If you are stuck on an older standard, you can replace it by fmt::format() from the fmt library.

#include <iostream>
#include <format>

int main() {
    constexpr const char* const a = "This is ";
    constexpr const char* const b = "a test.";

    std::string str = std::format("{}{}", a, b);
    std::cout << str << '\n';
}

Starting with C++17 std::string_view should be used instead of c-string-literals.

#include <iostream>
#include <format>
#include <string_view>

int main() {
    constexpr std::string_view a = "This is ";
    constexpr std::string_view b = "a test.";

    std::string str = std::format("{}{}", a, b);
    std::cout << str << '\n';
}

Starting with C++23 you should use std::print() (or std::println()) instead of std::cout. It makes sure your output is printed in the correct encoding. Especially in the Windows CMD std::cout causes problems as soon as you deviate from ASCII. std::print always works correctly.

#include <print>
#include <string_view>

int main() {
    constexpr std::string_view a = "This is ";
    constexpr std::string_view b = "a test.";

    std::println("{}{}", a, b);
}