c++ - 是否可以从不存在的实例中调用方法?

标签 c++

我正在处理的代码:

我有以下代码(ma​​in.cpp 中的索引有错误):

示例.hpp :

#ifndef SAMPLE_HPP
# define SAMPLE_HPP

# include <iostream>
# include <string>

class Sample{
public:
    Sample(void);
    ~Sample(void);
    void    tellname(void) const;
private:
    std::string     _name;
};

#endif

示例.cpp :

#include <iostream>
#include "Sample.hpp"

Sample::Sample(void){
    this->_name = "testname";
    return;
};

Sample::~Sample(void){
    return;
}

void    Sample::tellname(void) const{
    std::cout << "Name : " << this->_name << std::endl;
    return;
}

main.cpp

#include "Sample.hpp"

int     main(void){
    int     i;
    Sample  *test;

    test = new Sample[4];
    i = 0;
    while (i++ < 4)          // I know : i++; shouldn't be here
        test[i].tellname();
    delete [] test;
    return 0;
}

如果我编译它,我会得到以下输出:

Name : testname
Name : testname
Name : testname
Name :

我的问题是:

关于最后一行,它调用了一个方法 (void Sample::tellname(void)) 但来自不在表范围内的实例 ( test[4] 不存在)。

但是,它仍然调用 tellname(),即使它调用它的实例不存在。它只考虑它的 _name 字段是空的。

这怎么可能?

最佳答案

这只是未定义的行为,C++ 没有强加任何要求,所以“任何事情都可能发生”。您所看到的只是一个巧合,毫无意义:下次运行时它可能会崩溃,显示 nyan cat 等等。

关于c++ - 是否可以从不存在的实例中调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34633860/

相关文章:

c++ - 从未使用过分配给变量的 C/C++ 默认值/值

c++ - BOOST 版本 1.46.1 与 Visual Studio 2010 P.E

c++ - 如何在 CRTP 中调用派生模板函数?

c++ - 如何访问前向声明类的成员

c++ - Visual C++ 2010 代码完成

c++ - 如何将智能指针返回到成员变量?

c++ - 我可以在 Visual Studio 2012 中为不同平台(如 stm32 ARM 处理器)构建 C++ 代码吗

C++ : Best place to include header files

C++ 模板 : <class> does not name a type

c++ - boost::serialization::shared_ptr_helper 出错