gpt4 book ai didi

c++ - 从 vector 中获取超出范围的元素

转载 作者:行者123 更新时间:2023-11-28 00:14:08 25 4
gpt4 key购买 nike

<分区>

我正在做一些测试并解决了这个问题:

#include <stdio.h>

#include <vector>
#include <string>

class Person{
public:
std::string name;

Person(const char *name):
name(name){
printf("c-tor for %s\n", name);
};

void print(){
printf(">> %s\n", name.c_str());
};
};

int main(){
std::vector<Person> v;

v.push_back("Ivan");
v.push_back("Stoyan");
v.push_back("Dragan");

v[10].print();
}

如果我用 std::cout 来做,它会崩溃。但是,如果我用 printf 来做,它会打印:

c-tor for Ivan
c-tor for Stoyan
c-tor for Dragan
>> (null)

这是否“正确”工作只是偶然和巧合?

Portable programs should never call this function with an argument n that is out of range, since this causes undefined behavior.

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com