I have a class Foo with a static factory method - Foo::createOne - that creates an instance and puts some data into a private member variable of type std:vector. When I call Foo::createOne, my program throws this exception: "EXC_BAD_ACCESS (Could not access memory)"
Here is the code:
Foo.h
#include <vector>
class Foo {
public:
Foo();
Foo(const Foo& orig);
virtual ~Foo();
static Foo * createOne();
private:
std::vector<int> v;
};
Foo.cpp
#include "Foo.h"
Foo::Foo() {
};
Foo::Foo(const Foo& orig) {
};
Foo::~Foo() {
};
Foo * Foo::createOne() {
Foo *f;
f->v.push_back(5);
return f;
}
main.cpp
#include <iostream>
#include "Foo.h"
int main(int argc, char** argv) {
std::cout << "Testing createOne." << std::endl;
Foo *myFoo = Foo::createOne();
std::cout << "It worked." << std::endl;
}
Fixed one problem ...
Thanks for the answers. I fixed the uninitialized pointer problem (below). Now, I am getting a compiler warning "address of local variable 'f' returned"
Foo * Foo::createOne() {
Foo f;
f.v.push_back(5);
return &f;
}
Foo *f; f->v.push_back(5);what do you thinkfpoints to?main.newto them. A big difference is that if you use a variable unassigned in Java, the compiler treats it as an error; in C++ it's a warning. Another big difference is the need to calldelete.