Vector::at vs. vector::operator[] -- 不同的行为
Vector::at vs. vector::operator[] -- different behaviour
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
class sample
{
public:
sample()
{
cout << "consructor called" << endl;
}
void test()
{
cout << "Test function" << endl;
}
};
int main()
{
vector<sample> v;
sample s;
v.push_back(s);
try
{
v.at(1).test(); // throws out of range exception.
v[1000].test(); // prints test function
}
catch (const out_of_range& oor)
{
std::cerr << "Out of Range error: " << oor.what() << 'n';
}
return 0;
}
为什么v[1000].test();
在屏幕上打印测试功能。我在矢量中只添加了一个对象。我同意我可以访问v[1000]
因为它是顺序的。但是为什么它会给出完全正确的结果呢?提前谢谢。
vector::at(( 显式抛出越界异常,而 vector::operator 没有这样做。通过设计。
某些 std 实现支持在调试模式下检查运算符 [] 边界。
由于您的test()
方法不访问任何实例变量并且this
因此即使指向不存在的位置this
也可以毫无问题地执行它。
相关文章:
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 数据成员SFINAE的C++17测试:gcc vs clang
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 正在VS调试器中监视映射条目
- Confusion: decltype vs std::function
- 将IBM Rhapsody模型集成到VS 2019中
- VS Code "command":"make"与终端窗口中的命令行"make"不同
- 使用VS Code和CMake Tools运行自定义命令
- 如何处理来自核心指南检查器的关于gsl::at的静态分析警告
- 修改 VS Code 中的默认C++代码段
- 如何使用c++在VS 2019上运行SQL查询
- vs 2015 constexpr变量不恒定,但与2019相比还好吗
- "CID"在AT+HTTPPARA= "CID" ,1中是什么意思
- 完美前进使用 std::forward vs RefRefCast
- 从VS 2015更新3更新到VS2015更新3 d后浮点计算行为不同的原因
- Vector::at vs. vector::operator[] -- 不同的行为
- vector::at vs. vector::operator[]
- 在map/undered_map中使用find vs.at