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++编译器的工作。如果没有便携式解决方案,欢迎平台特定的黑客入侵。
做你想要什么目的,以防止施工从临时'的std :: string'? – Altainia
@Altainia:因为'str2.Str()'用悬空指针调用UB。 – Jarod42