为什么这个简单的C ++代码段错误? [英] Why does this simple C++ code segfault?

查看:46
本文介绍了为什么这个简单的C ++代码段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 a.h 标头:

#include <string>

template <typename L>
class A
{
    L l;

public:
    A() : l("a-text") {}
    const std::string get() const { l.get(); } // <<<< Edit: missing return!
};

这是 a.cpp :

#include "a.h"
#include <iostream>

class L {
    const std::string v;

public:
    L(const std::string& v_): v(v_) {}
    const std::string get() const { return v; }
};

int main() {
    L l("l-text");
    std::cout << l.get().c_str() << std::endl;

    A<L> a;
    std::cout << a.get().c_str() << std::endl; // <<<< - this will report Segmentation fault

    return 0;
}

第一个 std :: cout 可以正常显示 l-text 但是第二个 std :: cout 将报告分段错误,而不显示 a-text .

The first std::cout will work okay displaying l-text Yet the second std::cout will report Segmentation fault instead of displaying a-text.

提前谢谢!

推荐答案

打开警告.您在这里缺少 return 语句:

Turn on your warnings. You're missing a return statement here:

const std::string get() const { l.get(); }

这篇关于为什么这个简单的C ++代码段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆