C# "var"和C++ "auto"之间的差异
Differences between C# "var" and C++ "auto"
我现在正在学习C ,因为我需要编写一些低级程序。
当我了解auto
关键字时,它使我想起了C#的var
关键字。
那么,C#var
和C auto
的区别是什么?
c#var关键字仅在函数内部本地工作:
var i = 10; // implicitly typed
在C 自动关键字中,不仅可以在变量中推导类型,还可以在函数和模板中推导类型:
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;
}
从性能的角度来看,C 中的自动关键字不会影响运行时性能。var关键字也不会影响运行时性能。
IDE的Intellisense支持可能是另一个区别。C#中的VAR关键字可以轻松推导,您将看到带有鼠标的类型。使用C 中的自动关键字,它可能更复杂,这取决于IDE和工具。
要简单地说, auto
比 var
要复杂得多。
首先,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
用作函数声明中的尾声返回类型语法的一部分:
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));
它们是等效的。它们都可以让您自己指定变量的类型,但是变量保持强劲的型。以下行在C#中等效:
var i = 10; // implicitly typed
int i = 10; //explicitly typed
,以下行在C 中等效:
auto i = 10;
int i = 10;
但是,您应该记住,在C 中,auto
变量的正确类型是使用函数调用的模板参数扣除规则来确定的。
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- int(c) 和 c-'0' 之间的区别。C++
- 在cuda线程之间共享大量常量数据
- 在c代码之间共享数据的最佳方式
- Mix_Init和Mix_OpenAudio SDL之间的区别是什么
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 大小相等但成员数量不同的结构之间的性能差异
- 类与私有变量的其他类之间的线程安全性
- 如何在cpp文件之间切换窗口?在Qt中
- 线程之间的布尔停止信号
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 在 const 函数中通过引用和指针返回之间的区别
- 我想知道长双倍和双倍之间的区别
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 构造函数和转换运算符之间的重载解析
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数