我偶然发现了一个奇怪的c ++片段.我认为这是错误的代码.为什么有人会在函数内重复函数声明?它甚至在更改类型签名时unsigned int sum(int, int)生成预期结果4294967294j.为什么这甚至编译?
#include <iostream>
#include <typeinfo>
using namespace std;
int sum(int a, int b){
return a + b;
}
int main()
{
int sum(int, int); // redeclaring sum???
int a = -1;
auto result = sum(a, a);
cout << result << typeid(result).name() << endl;
}
Run Code Online (Sandbox Code Playgroud)
编辑:它为我编译...但它是有效的C++代码?如果没有,为什么编译器(mingw 4.8.1)允许它?
我将函数的某些返回值绑定到const左值引用,但是在const lvalue引用的生命周期结束之前删除了该对象.
在以下示例中,Foo对象在foo结束的生命周期之前被销毁:
#include <iostream>
#include <string>
struct Foo
{
~Foo()
{
std::cout << "Foo destroyed: " << name << std::endl;
}
std::string name;
};
Foo&& pass_through(Foo&& foo)
{
return std::move(foo);
}
int main()
{
const Foo& foo = pass_through({"some string"});
std::cout << "before scope end" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
Foo被破坏:
范围结束前的一些字符串
住在coliru:1
我以为你可以绑定const T&任何东西.返回是不好的做法T&&,应该按价值返回?
我在这里的cpprestsdk偶然发现了这个:
inline utility::string_t&& to_string_t(std::string &&s) { return std::move(s); }
Run Code Online (Sandbox Code Playgroud)
https://github.com/Microsoft/cpprestsdk/blob/master/Release/include/cpprest/asyncrt_utils.h#L109
非常混乱,因为Windows版本to_string_t(由预处理器宏调度)返回值:
_ASYNCRTIMP utility::string_t __cdecl …Run Code Online (Sandbox Code Playgroud)