'push_back crashed when using std::vector if the type only defined copy constructor with c++11
The code like this:
#include <iostream>
#include <vector>
struct Foo
{
int i;
double d;
};
class Boo
{
public:
Boo() : fptr(nullptr)
{
std::cout << "Boo default construct..." << std::endl;
}
Boo(int i, double d):fptr(new Foo{i,d})
{
}
Boo(const Boo &rhs) :fptr(new Foo{rhs.fptr->i,rhs.fptr->d})
{
}
Foo *fptr;
};
int main(int argc, char const *argv[])
{
std::vector<Boo> vec(1);
Boo b(42, 10.24);
vec.push_back(b);
return 0;
}
Env: Ubuntu 16.4 LTS with gcc 5.4 g++ -std=c++11 test.cpp -o test -g
./test
If define move constructor,this will work good. I debuged it several hours but can not found what's wrong with it, maybe because some rules in c++ 11 that i did't know.
Could somebody help me? Thanks!
Solution 1:[1]
Your Boo copy constructor derefernces a pointer fptr that may be null.
A std::vector::push_back may reallocate vector storage. Reallocating may use copy constructors.
That is what is happening in your program. You are copying a Boo that has a null pointer.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
