Hi guys,

I have a static vector which holds objects of a class. I want this vector to be singleton i.e. be the only vector of this type which will indefinitely store the relevant objects.

Unfortunately, a problem arises whereby, when I access the vector from a different class, for some reason it "loses" it's contents and is empty?

>>a problem arises whereby, when I access the vector from a different class, for some reason it "loses" it's contents and is empty?
<<

From what content?

How about you make a adapter class, that wraps vector, and make that
adapter class singleton.

Hi there and thanks for the response. In the program, I navigate to an 'add book' GUI panel (A) which adds books to the vector. I then want to navigate to another panel (B) and populate a combobox using the contents of the vector. The vector remains populated in panel A but not B.

In short,
Home->Panel A->Home->Panel A the vector is fine
Home->Panel A->Home->Panel B then the vector appears empty

I tried to wrap the vector in a singleton class before trying to access the vBooks vector through the class as follows:

class SingletonVector
{
public:
	static vector<Book> vBooks;
	SingletonVector() {};
                     
};
SingletonVector sv;
Book b;
b.setTitle("Test title");
sv->vBooks.push_back(b); // PROBLEM LINE

The code compiles fine apart from when I use the function 'push_back' which results in the following error:

error LNK2001: unresolved external symbol "public: static class std::vector<class Book,class std::allocator<class Book> > SingletonVector::vBooks" (?vBooks@SingletonVector@@2V?$vector@VBook@@V?$allocator@VBook@@@std@@@std@@A)
vc_mswd\myapp.exe : fatal error LNK1120: 1 unresolved externals

use SingletonVector::vBooks.push_back(b);

commented: Thanks for the replies mate +1

Still no go..feels like the fix is not much further!

MainFrame.obj : error LNK2001: unresolved external symbol "public: static class std::vector<class Book,class std::allocator<class Book> > SingletonVector::vBooks" (?vBooks@SingletonVector@@2V?$vector@VBook@@V?$allocator@VBook@@@std@@@std@@A)
Reports.obj : error LNK2001: unresolved external symbol "public: static class std::vector<class Book,class std::allocator<class Book> > SingletonVector::vBooks" (?vBooks@SingletonVector@@2V?$vector@VBook@@V?$allocator@VBook@@@std@@@std@@A)
vc_mswd\myapp.exe : fatal error LNK1120: 1 unresolved externals

I can only get rid of the linker errors by deleting any code that works on the vector i.e. push_back / .at

What am I missing..

:(

Finally!

The problem was that I wasn't fully declaring the static variable outside the scope of the class before using it!

Thanks for the help fp

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.