C# "var" 和 C++ "auto" 之间的差异

Differences between C# "var" and C++ "auto"

我现在正在学习C++,因为我需要编写一些低级程序。

当我了解到 "auto" 关键字时,它让我想起了来自 C# 的 "var" 关键字。

那么,C# "var" 和 C++ "auto" 有什么区别?

它们是等价的。它们都允许您不自己指定变量的类型,但变量保持强类型。以下几行在 C# 中是等效的:

var i = 10; // implicitly typed  
int i = 10; //explicitly typed  

下面几行在 C++ 中是等价的:

auto i = 10;
int i = 10;

但是,您应该记住,在 c++ 中,auto 变量的正确类型是使用函数调用的模板参数推导规则确定的。

在 C# 中,var 关键字仅在函数内部有效:

var i = 10; // implicitly typed 

在 C++ auto 关键字中 can deduce 不仅在变量中键入,而且在函数和模板中键入:

auto i = 10;

auto foo() { //deduced to be int
    return 5;
}

template<typename T, typename U>
auto add(T t, U u) {
    return t + u;
}

从性能的角度来看,auto keyword in C++ does not affect runtime performance. And var keyword does not affect runtime performance as well

另一个不同之处在于 IDE 中的智能感知支持。 C# 中的 Var 关键字可以很容易地推断出来,您将看到鼠标悬停的类型。在 C++ 中使用 auto 关键字可能会更复杂,它取决于 IDE.

简单来说,autovar 复杂得多。

首先,auto可能只是推导类型的一部分;例如:

std::vector<X> xs;
// Fill xs
for (auto x : xs) x.modify(); // modifies the local copy of object contained in xs
for (auto& x : xs) x.modify(); // modifies the object contained in xs
for (auto const& x : xs) x.modify(); // Error: x is const ref

其次,auto可用于一次声明多个对象:

int f();
int* g();
auto i = f(), *pi = g();

第三,auto 用作函数声明中尾部 return 类型语法的一部分:

template <class T, class U>
auto add(T t, U u) -> decltype(t + u);

它也可以用于函数定义中的类型推导:

template <class T, class U>
auto add(T t, U u) { return t + u; }

四、以后可能开始用于声明函数模板:

void f(auto (auto::*mf)(auto));
// Same as:
template<typename T, typename U, typename V> void f(T (U::*mf)(V));