[英]Warning C4172 returning address of local variable or temporary. But I return a input argument value
I designed a template class which can operate several kinds of strings, such as CString and std::string. 我设计了一个模板类,它可以操作多种字符串,例如CString和std :: string。 I have been using it long time, and it works fine.
我已经使用了很长时间,而且效果很好。 But the "return str[i]" in "at" function led to a warning C4172, that means I return an address of local varible.
但是“ at”函数中的“ return str [i]”导致警告C4172,这意味着我返回了本地变量的地址。 But the str isn't a local varible.
但是str不是局部变量。 It should be passed from the outside.
它应该从外面传递。 How can I make the compile not prompt the warning?
如何使编译器不提示警告?
template<class TSTR, typename TCHR>
class stringOpr
{
public:
typedef typename TSTR TSTRING;
typedef typename TCHR TCHARTYPE;
virtual const TCHARTYPE& at(const TSTRING& str, int i) const
{
return str[i];//Warning C4172
}
...
};
That warning makes sense. 该警告是有道理的。 If there is a MyString that the operator of it didn't return a reference.
如果存在MyString,则其运算符未返回引用。
class MyString
{
char operator[](int i) const;
};
This function will crash. 此功能将崩溃。 In this case, you should rewrite your "at" function to fit a returning reference.
在这种情况下,您应该重写“ at”函数以适合返回的引用。 If you really want to return a reference, do this,
如果您确实要返回参考,请执行此操作,
#pragma warning(disable : 4172)
virtual const TCHARTYPE& at(const TSTRING& str, int i) const
{
return str[i];
#pragma warning(default : 4172)
}
Ignore the warning, and re-enable it after this. 忽略警告,然后重新启用它。
/ ---------------------------------------------------- / / ------------------------------------------------- - /
CString::operator[] really doesn't return a reference. CString :: operator []确实不返回引用。 So I make a concession
所以我让步
virtual /*const*/ TCHARTYPE/*&*/ at(const TSTRING& str, int i) const
{
return str[i];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.