问题。
请参阅下面的代码...我缺少 return field;
语句并且在几次调试运行中没有发现它。我从来没有想过像这样的东西会毫无错误地通过编译器!为什么这样做?
描述
我有一个解析器对象,它使用 std::tr1::function
来接收构建时的翻译算法。翻译从字符串转换为TransportableMessage
类型的对象,它由TMFields
组成,可以容纳不同的类型。所以无论如何我为创建字段创建了一个工厂函数,因为字段的类型是基于字符串(来自 XML)的,虽然现在只有几个,但将来可能会有更多。
tstring
对象是基于 UNICODE
的类型转换,基本上立即解析为 std::wstring
。另外因为我使用的是 VS2008 unique_ptr
不存在所以我将 std::auto_ptr
隐藏在 ScopedPtr_t
后面以使升级更容易,因此更有可能发生。
namespace arc
{
namespace util
{
int internalTest()
{
std::cout << "Any error?" << std::endl;
}
ScopedPtr_T<TMField> TmFieldFactory( const tstring& name, const tstring& typeName, const tstring& value )
{
ScopedPtr_T<TMField> field;
int a = internalTest();
if( typeName == _T("int") || typeName == _T("long") )
{
field.reset( new TMNumericField( name, boost::lexical_cast<__int64>(value) ) );
}
else if( typeName == _T("string") )
{
field.reset( new TMStringField( name, value ) );
}
else if( typeName == _T("timestamp") )
{
field.reset( new TMTimeField( name, boost::lexical_cast<__int64>(value) ) );
}
else
{
std::string info( __FILE__ " :: " __FUNCTION__ " : Unrecognized TmField type ");
std::string type( typeName.begin(), typeName.end() );
info += type;
throw ARC_Exception( info.c_str() );
}
return field; // I WAS MISSING THIS!
}
}
}
基本上我想知道是否还有其他人遇到过这个问题?我引入了函数 internalTest
来查看问题是否特定于 scoped_ptr
,但似乎并非如此。我还尝试在 GCC 中使用 internalTest
,但它返回了一个错误。
为什么 Visual Studio 没有标记这个?我是否缺少可以打开的编译设置?标准允许这样做吗?抱歉,如果这是众所周知的事情,我在谷歌上搜索并在这里寻找答案。
EDIT::调用代码 - 只需添加它以获得更多上下文。
SharedPtr_T<TransportableMessage> strToTmConvFunc_Default_Apc7_0(const std::string& tm_str)
{
pugi::xml_document xmlDoc;
if( false == xmlDoc.load( tm_str.c_str() ) )
{
ARC_LOG(LOG_WARN, "The passed TM object was malformed. %s", tm_str.c_str() );
throw ARC_Exception( "Malformed Transportable Message XML" );
}
pugi::xml_node tmBase = xmlDoc.first_child();
std::string xmlRootName( tmBase.name() );
if( xmlRootName.compare("TM") != 0 )
{
ARC_LOG(LOG_WARN, "The passed TM object was malformed. %s", tm_str.c_str() );
throw ARC_Exception( "Malformed Transportable Message XML" );
}
std::string tmname = tmBase.child("N").child_value();
std::string entity = tmBase.child("E").child_value();
ARC_LOG(LOG_INFO, "TM message received for parsing. TM name is %s", tmname.c_str() );
tstring t_tmname( tmname.begin(), tmname.end() );
SharedPtr_T<TransportableMessage> tm_obj( new TransportableMessage( t_tmname, 0 ) );
pugi::xml_node fields = tmBase.child("FS");
for( pugi::xml_node field = fields.first_child(); field; field = field.next_sibling("field") )
{
tm_obj->addField( arc::util::TmFieldFactory( field.child_value("N"), field.child_value("T"), field.child_value("V") ) );
}
return tm_obj;
}
最佳答案
在没有返回值的情况下脱离函数体不是错误,而是未定义的行为;参见 6.3.3 return
语句 [stmt.return] §3:
Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.
关于c++ - Visual Studio - 返回值失败时没有编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11851468/