我刚刚读到了C++ 14中提供的名为"返回类型推导"的新功能,我对该类型函数的递归有疑问.我已经了解到,该函数的第一次返回必须允许推导返回类型.
Wiki提供的示例完全符合该规则.
auto Correct(int i) {
if (i == 1)
return i; // return type deduced as int
else
return Correct(i-1)+i; // ok to call it now
}
auto Wrong(int i) {
if (i != 1)
return Wrong(i-1)+i; // Too soon to call this. No prior return statement.
else
return i; // return type deduced as int
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:为什么当我换Wrong(int i)到Wrong(auto i),Wrong功能开始编制?隐藏在这个微小变化背后的是什么?
我现在正在研究C++ 11中的线程,我遇到了以下代码:
lock_guard<mutex> lg(mutex);
Run Code Online (Sandbox Code Playgroud)
没有变数mutex.mutex只是类型的名称.
任何人都可以解释我上面的代码行如何工作?
为什么编译器(GCC)不会打印任何错误?
完整代码:
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
using namespace std;
void do_something()
{
lock_guard<mutex> lg(mutex);
cout << "Working..." << endl;
this_thread::sleep_for(chrono::milliseconds(3000));
}
int main()
{
thread thd(do_something);
thd.join();
}
Run Code Online (Sandbox Code Playgroud)