Sunius Sunius - 1 month ago 4
C++ Question

Prevent passing temporary object as an argument to a function

Suppose I have this:

template <typename CharType>
class StringView
const CharType* m_String;
size_t m_Length;

template <typename CharTraits, typename StringAlloc>
inline StringView(const std::basic_string<CharType, CharTraits, StringAlloc>& str) :
m_String(str.c_str()), m_Length(str.length())

inline const CharType* Str() const
return m_String;

Is there a way to prevent construction from a temporary
? That is:

std::string GetStr()
return "hello";

int main()
std::string helloString = "hello";
StringView<char> str1 = helloString; // This is ok
StringView<char> str2 = GetStr(); // I want this to be a compiler error

std::cout << str1.Str() << std::endl;
std::cout << str2.Str() << std::endl;

I need this to work on at least VS 2015 C++ compiler. Platform specific hacks are welcome if there's no portable solution.


You may delete the constructor:

template <typename CharTraits, typename StringAlloc>
StringView(std::basic_string<CharType, CharTraits, StringAlloc>&&) = delete;