小编Mar*_*kus的帖子

在函数内部重新定义函数

我偶然发现了一个奇怪的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)允许它?

c++

12
推荐指数
1
解决办法
382
查看次数

为什么我不能将const左值引用绑定到返回T &&的函数?

我将函数的某些返回值绑定到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)

c++ move-semantics c++11

8
推荐指数
1
解决办法
308
查看次数

标签 统计

c++ ×2

c++11 ×1

move-semantics ×1