从内部类访问const函数时出现分段错误

时间:2019-04-23 22:12:40

标签: c++11

从内部类访问const成员时,无法理解为什么会出现分段错误。

程序:

#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

typedef struct
{
    double a;
    double b;
} conf;

class configuration
{
   public:
    configuration(const conf *conf) : conf_(conf) {}
    double
    getA() const
    {
        return conf_->a;
    }
    double
    getB() const
    {
        return conf_->b;
    }

   private:
    const conf *conf_;
};

class Test
{
   private:
    class TestInner
    {
       public:
        TestInner(const configuration *conf) : conf_(conf) {}

        void
        print()
        {
            cout << "INNER START\n";
            cout << "Innerclass data: a : " << conf_->getA()
                 << "b : " << conf_->getB() << "\n";
            cout << "INNER END\n";
        }

       private:
        const configuration *conf_;
    };

   private:
    const configuration *conf_;
    typedef std::unordered_map<std::string, TestInner *> TestInners;
    TestInners testInners_;
    const std::string key_;

   public:
    Test(const configuration *conf);
    void
    print();
};

Test::Test(const configuration *conf) : conf_(conf), key_("ABC")
{
    TestInner testInner_(conf);

    testInners_.insert(std::pair<std::string, TestInner *>(key_, &testInner_));
}

void
Test::print()
{
    cout << "Test data: a : " << conf_->getA() << "b : " << conf_->getB()
         << "\n";

    TestInners::const_iterator testInner = testInners_.find(key_);
    testInner->second->print();
}

int
main()
{
    conf conf_;
    conf_.a = 10;
    conf_.b = 10;

    configuration configuration_(&conf_);
    Test test(&configuration_);

    test.print();

    cout << "Hello World";

    return 0;
}

输出:

测试数据:a:10b:10
内部开始
分段错误(核心已转储)

这似乎与编译器有关,

1.On g ++(GCC)4.4.6 20110731(Red Hat 4.4.6-3)

Output: 

Test data: a : 10b : 10
INNER START
Innerclass data: a : 3.15654e-317b : 6.95271e-310
INNER END
Hello World%   

2。在Apple LLVM版本9.0.0(clang-900.0.39.2)

Output:

Test data: a : 10b : 10
INNER START
Innerclass data: a : 10b : 10
INNER END
Hello World
  1. x86_64-pc-linux-gnu-g ++(GCC)7.4.0中的分段错误

1 个答案:

答案 0 :(得分:1)

在堆栈上获取变量的地址并在方法退出后使用该值将导致未定义的行为。将值移到堆上将解决此问题,但可能需要稍后在Test dtor中进行清理

Test::Test(const configuration *conf) : conf_(conf), key_("ABC")
{
    TestInner testInner_* = new TestInner(conf);

    testInners_.insert(std::pair<std::string, TestInner *>(key_, testInner_));
}