I am doing some tests and got around this:
#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();
}
If I do it with std::cout
, it crashes. However if I do it with printf
, it prints:
c-tor for Ivan
c-tor for Stoyan
c-tor for Dragan
>> (null)
Is this working "correctly" just by chance and coincidence?
Portable programs should never call this function with an argument n that is out of range, since this causes undefined behavior.