防止将临时对象作为参数传递给函数

Prevent passing temporary object as an argument to a function

假设我有这个:

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

public:
    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;
    }
};

有没有办法阻止临时std::string的构建?即:

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;   
}

我需要它至少在 VS 2015 C++ 编译器上工作。如果没有可移植的解决方案,欢迎针对特定平台进行黑客攻击。

您可以删除构造函数:

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