这两个代码块有什么区别?
我问这个问题是因为只有带括号的那个代码会打印一次"Here",而不带括号的代码会打印三次。括号的意思和作用是什么?这种使用括号的语法有一个名称吗?
struct HighResClock
{
typedef long long rep;
typedef std::nano period;
typedef std::chrono::duration<rep, period> duration;
typedef std::chrono::time_point<HighResClock> time_point;
static const bool is_steady = true;
static time_point now();
};
namespace
{
auto g_Frequency = []() -> long long
{
std::cout<<"HERE";
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
return frequency.QuadPart;
}();
}
HighResClock::time_point HighResClock::now()
{
LARGE_INTEGER count;
QueryPerformanceCounter(&count);
return time_point(duration(count.QuadPart * static_cast<rep>(period::den) / g_Frequency));
}
int main()
{
HighResClock c;
c.now();
c.now();
c.now();
}
并且
struct HighResClock
{
typedef long long rep;
typedef std::nano period;
typedef std::chrono::duration<rep, period> duration;
typedef std::chrono::time_point<HighResClock> time_point;
static const bool is_steady = true;
static time_point now();
};
namespace
{
auto g_Frequency = []() -> long long
{
std::cout<<"HERE";
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
return frequency.QuadPart;
};
}
HighResClock::time_point HighResClock::now()
{
LARGE_INTEGER count;
QueryPerformanceCounter(&count);
return time_point(duration(count.QuadPart * static_cast<rep>(period::den) / g_Frequency()));
}
int main()
{
HighResClock c;
c.now();
c.now();
c.now();
}
如果您没有注意到,区别在于下面的括号:
auto g_Frequency = []() -> long long
{
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
return frequency.QuadPart;
}(); //this bracket here appears in one and not the other..
我问这个问题是因为只有带括号的那个代码会打印一次"Here",而不带括号的代码会打印三次。括号的意思和作用是什么?这种使用括号的语法有一个名称吗?
= []()
是什么..抱歉,通常在结尾处使用()
表示执行而不是分配值。 - Noam Rathaus