我听说在初始化之前访问let和const值可能会导致ReferenceError因为称为时间死区的东西.
什么是暂时死区,它与范围和吊装有什么关系,以及在什么情况下遇到?
作为一名新手C++程序员,有些结构对我来说仍然非常模糊,其中之一就是const.你可以在很多地方使用它,并且有很多不同的效果,初学者几乎不可能活着出来.一些C++专家会永远解释各种用途以及是否和/或为什么不使用它们?
const的目的是什么?
const Object myFunc(){
return myObject;
}
Run Code Online (Sandbox Code Playgroud)
我刚刚开始阅读Effective C++,而第3项提倡这一点,Google搜索也提出了类似的建议,但也有反作用.我看不出在这里使用const会更好.假设需要按值返回,我认为没有任何理由保护返回的值.给出为什么这可能有用的示例是防止返回值的意外bool强制转换.实际问题是应该使用explicit关键字来防止隐式bool强制转换.
在这里使用const可以防止在没有赋值的情 所以我无法用这些对象执行算术表达式.似乎没有一个未命名的const有用的情况.
在这里使用const获得了什么,何时更可取?
编辑:将算术示例更改为修改在分配之前可能要执行的对象的任何函数.
a const_iterator和an 之间的区别是什么iterator?你在哪一个使用另一个?
我想知道它们之间的区别
const int* ptr;
Run Code Online (Sandbox Code Playgroud)
和
int * const ptr;
Run Code Online (Sandbox Code Playgroud)
以及它是如何工作的.
我很难理解或记住这一点.请帮忙.
我听说const意味着线程安全的C++ 11.真的吗?
这是否意味着const现在是等效的Java的synchronized?
他们的关键字用完了吗?
你有没有恨它
class Foobar {
public:
Something& getSomething(int index) {
// big, non-trivial chunk of code...
return something;
}
const Something& getSomething(int index) const {
// big, non-trivial chunk of code...
return something;
}
}
Run Code Online (Sandbox Code Playgroud)
我们无法使用另一个方法实现这两种方法,因为您无法const从const版本中调用非版本(编译器错误).演员将被要求const从非const一个版本调用该版本.
有没有一个真正优雅的解决方案,如果没有,最接近一个?
快速提问:
int testfunc1 (const int a)
{
return a;
}
int testfunc2 (int const a)
{
return a;
}
Run Code Online (Sandbox Code Playgroud)
这两个功能在每个方面都是相同的还是有区别的?我对C语言的答案感兴趣,但如果C++语言中有一些有趣的东西,我也想知道.
sort(mMyClassVector.begin(), mMyClassVector.end(),
[](const MyClass & a, const MyClass & b)
{
return a.mProperty > b.mProperty;
});
Run Code Online (Sandbox Code Playgroud)
我想使用lambda函数来排序自定义类来代替绑定实例方法.但是,上面的代码会产生错误:
错误C2564:'const char*':对内置类型的函数式转换只能接受一个参数
它工作得很好boost::bind(&MyApp::myMethod, this, _1, _2).
以下代码表示将map传递const给operator[]方法会丢弃限定符:
#include <iostream>
#include <map>
#include <string>
using namespace std;
class MapWrapper {
public:
const int &get_value(const int &key) const {
return _map[key];
}
private:
map<int, int> _map;
};
int main() {
MapWrapper mw;
cout << mw.get_value(42) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是因为地图访问中可能出现的分配吗?没有地图访问的函数可以声明为const吗?
MapWrapper.cpp:10: error: passing ‘const std::map<int, int, std::less<int>, std::allocator<std::pair<const int, int> > >’ as ‘this’ argument of ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = int, _Tp = int, _Compare = std::less<int>, _Alloc …