Visual C++ 2010接受:
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
for each (auto i in v)
std::cout << i << std::endl;
Run Code Online (Sandbox Code Playgroud)
这是C++ 11功能还是Microsoft扩展?根据维基百科,C++ 11 for-each循环的语法不同:
int myint[] = {1,2,3,4,5};
for (int& i: myint)
{
std::cout << i;
}
Run Code Online (Sandbox Code Playgroud) 当 C# 程序持有命名信号量时,如果应用程序提前终止(例如通过按 Ctrl+C 或关闭控制台窗口),它似乎不会被释放。至少在进程的所有实例都终止之前不会。
在这种情况下,使用命名互斥量会引发 AbandonedMutexException,但不会引发信号量。当另一个程序实例提前终止时,如何防止一个程序实例停顿?
class Program
{
// Same with count > 1
private static Semaphore mySemaphore = new Semaphore(1, 1, "SemaphoreTest");
static void Main(string[] args)
{
try
{
// Blocks forever if the first process was terminated
// before it had the chance to call Release
Console.WriteLine("Getting semaphore");
mySemaphore.WaitOne();
Console.WriteLine("Acquired...");
}
catch (AbandonedMutexException)
{
// Never called!
Console.WriteLine("Acquired due to AbandonedMutexException...");
}
catch (System.Exception ex)
{
Console.WriteLine(ex);
}
Thread.Sleep(20 * 1000);
mySemaphore.Release();
Console.WriteLine("Done");
}
}
Run Code Online (Sandbox Code Playgroud) 什么时候可以省略 C++ 模板参数列表?例如,在 Visual Studio 2010 中,这段代码可以正常编译:
template<class T>
Vec2<T> Vec2<T>::operator+ (const Vec2 &v) const
{
return Vec2(x + v.x, y + v.y);
}
Run Code Online (Sandbox Code Playgroud)
如果您内联代码,它实际上会在没有任何参数列表的情况下进行编译。但这真的和下面的版本一样吗?
template<class T>
Vec2<T> Vec2<T>::operator+ (const Vec2<T> &v) const
{
return Vec2<T>(x + v.x, y + v.y);
}
Run Code Online (Sandbox Code Playgroud)