use*_*491 2 c++ constructor vector segmentation-fault c++11
我面临一个奇怪的问题:我无法正确地重置(破坏和构造)包含向量的属性.尝试访问向量时会导致分段错误.
这是我的代码(在C++ 11中使用).我认为我最简化它可以强调这个问题,但我可能错了,对不起.目标是打印两次不同(随机)矢量两次.第一个矢量运行良好,第二个矢量完全失败,原因不明.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
class A
{
std::vector<int> n;
public :
A();
std::string toString() const;
};
A::A()
{
for (int i = 0; i < 10; i++)
n.push_back(std::rand()%10);
}
std::string A::toString() const
{
for (auto i : n)
std::cout << i << ' ';
std::cout << std::endl;
}
class B
{
A a;
public :
void resetA();
A getA() const;
};
void B::resetA()
{
a = A();
}
A B::getA() const
{
return a;
}
int main()
{
srand(time(NULL));
B b;
std::cout << b.getA().toString();
b.resetA();
std::cout << b.getA().toString();
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,我想尽可能避免指针和动态分配.它更符合我的UML概念.
而且,当使用简单的int(无向量)时,此代码运行良好.
谢谢.
你toString()
没有返回任何东西,所以你的程序有未定义的行为(实际上,返回随机垃圾,这肯定不是一个有效的std::string
对象).
也许你想使用字符串流代替?
#include <sstream>
// ...
std::string A::toString() const
{
std::ostringstream s;
for (auto i : n)
s << i << ' ';
s << '\n';
return s.str();
}
Run Code Online (Sandbox Code Playgroud)
实例.
一般来说,编译尽可能多的警告是一个好主意.这肯定会被报告为警告.对于这个特殊警告(无void
功能不返回任何内容),我强烈建议将其视为错误.