2016-09-20 5 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

으로 임시'표준 : string'에서 건축을 방지하고자 할 것을 끝? – Altainia

+0

@Altainia :'str2.Str()'이 매달려있는 포인터로 UB를 호출하기 때문입니다. – Jarod42

답변

6

당신은 생성자를 삭제할 수 있습니다 :

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

감사합니다. 솔루션이 완벽하게 작동합니다. – Sunius