从类返回一个字符串 — 奇怪的行为
Return a string from class — weird behavior
大约10 年前,我有点喜欢 c++ 编码,但从未真正爱上它。但是我现在的一个项目需要 c++(所以我对 c++ 有一点了解,但我不是深度专家)。我浏览了我的旧笔记和代码片段,让代码做我想做的事——除了一件事:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class B
{
private:
string ns;
public:
B(string ms) {ns = ms;}
string gets() {return ns;}
};
class A
{
private:
vector<B> nb;
public:
A(vector<B> mb) {nb = mb;}
vector<B> getb() {return nb;}
};
int main(int argc, char **argv)
{
B b0 = B("zero");
B b1 = B("one");
B b2 = B("two");
B b3 = B("three");
A a = A({b0, b1, b2, b3});
cout << endl << endl;
for(auto it = a.getb().begin(); it != a.getb().end(); ++it)
cout << it->gets() << " ";
return 0;
}
运行此代码 (g++ -std=c++11 main.cpp) 会导致
在抛出"std::bad_alloc">
what(): std::bad_alloc 已中止(核心转储)后调用的终止
错误。这已经很奇怪了,因为这基本上只是我的笔记的副本(但是,它在笔记中返回一个整数而不是字符串)。如果我让函数返回ns.c_str()
它几乎可以工作,我得到
齐一二三
有趣的是,这只是在循环中发生。使用(a.getb().begin())->gets()
给了我正确的值("零")。这种奇怪行为的解释是什么?
a.getb().begin()
中的每个getb()
和a.getb().end()
返回原始向量的单独副本。将来自一个向量的迭代器与来自另一个向量的迭代器进行比较是不好的。
您可以将getb()
方法更改为类似的东西。
const vector<B>& getb() const {return nb;}
现在,begin()
和end()
调用将在同一向量上工作。
或者使用更友好的基于范围的 c++11 循环:
for (var b in a.getb()) {
cout << b.gets() << " ";
哪个为您做.begin()
、.end()
和++
。
如果你绝对想使用旧式的 for 循环,而不是改变你的getb()
方法,你也可以这样做:
auto b_copy = a.getb();
for(auto it = b_copy.begin(); it != b_copy.end(); ++it)
cout << it->gets() << " ";