2016-09-20 31 views
0

假設我有這樣的:防止通過臨時對象作爲參數傳遞給函數

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++編譯器的工作。如果沒有便攜式解決方案,歡迎平臺特定的黑客入侵。

+0

做你想要什麼目的,以防止施工從臨時'的std :: string'? – Altainia

+0

@Altainia:因爲'str2.Str()'用懸空指針調用UB。 – Jarod42

回答

6

您可以刪除構造:

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

謝謝,您的解決方案完美地工作。 – Sunius

相關問題