c++ - 更改一个类属性的数据类型会导致在构造子类对象期间出现段错误

标签 c++ constructor segmentation-fault subclass

此版本的代码运行良好:

class Object
{
public:

    // Object( string name, string state ) <-- string version
    Object( string name, bool state )
    {
        this->name = name ;
        this->state = state ;
    }

protected:
    string name ;
    bool state ;
    // string state ; <-- string version
};



class Tool : public Object
{
public:
    Tool(string name):Object(name,state)
    {
        this->state = true ;

        //this->state = "true" ; <-- string version
    }
};


int main ()
{

    Tool* tool = new Tool("name") ;


    cin.get() ;
    return 0 ;
}

...但是如果我将 state 属性设置为 string (并用我注释掉的附近的“字符串版本”替换代码行),那么,之后编译没有问题,程序在运行时出现段错误。

创建基类对象时没有问题。

调试器输出:

#0 0x45b74c std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) () (??:??)
#1 ??   ?? () (??:??)

为什么将state设为string会导致问题?

最佳答案

Tool(string name):Object(name,state)

您尝试使用未初始化的成员state(基类Objectprotected成员)作为的参数code>Object 的构造函数,它应该由 Object 的构造函数初始化。使用未初始化的变量会导致 UB,意味着任何事情都可能发生。在您的情况下,使用 std::string 时会导致段错误。

顺便说一句:您应该收到一个编译警告。如clang with -Wall .

source_file.cpp:28:35: warning: base class 'Object' is uninitialized when used here to access 'Object::state' [-Wuninitialized]
    Tool(string name):Object(name,state)
                                  ^

关于c++ - 更改一个类属性的数据类型会导致在构造子类对象期间出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36517474/

相关文章:

c++ - C++ 变量的定义,Basic/6 部分

c++ - 创建异常时构造函数语法的差异 (c++)

Javascript 创建具有 new 和不具有 new + 继承的对象

c++ - GMP mpf 函数导致段错误

c++ - LNK2005错误,已经定义: Possibly one definition rule violation?

c++ - 是否有任何关于从 C 迁移到 C++ 的指南

c++ - 使用 const 在 C++ 中进行模板特化

c# - 重载构造函数 C#

c - 段错误spoj协助

c++ - 打开 g++ 优化会导致段错误 - 我不明白