Grz*_*orz -6 c++ templates std
这是啊标题:
#include <string>
template <typename L>
class A
{
L l;
public:
A() : l("a-text") {}
const std::string get() const { l.get(); } // <<<< Edit: missing return!
};
Run Code Online (Sandbox Code Playgroud)
这是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;
}
Run Code Online (Sandbox Code Playgroud)
第一个std::cout将正常显示l-text
然而第二个std::cout将报告分段错误而不是显示文本.
提前致谢!
打开你的警告.你在return这里错过了一个声明:
const std::string get() const { l.get(); }
Run Code Online (Sandbox Code Playgroud)