As the title says please.

The issue I'm having is I've got a class which holds the vector. When I create a new instance of the class I assume a new vector is also created which results in the vector losing all its contents?

Dani AI

Generated

Short answer: if your vector is a normal (non-static) member, each new object gets its own vector — that explains why saw the contents disappear when a new instance was created. To share a single vector across the program, common options are: a program-level global, a class-level shared member, or a function-local static (Meyers singleton). was pointing in the class-level direction; below are concise, safe patterns and pitfalls to watch for.

Global (header + single definition)

// globals.h
#pragma once
#include <vector>
extern std::vector<int> g_values;

// globals.cpp
#include "globals.h"
std::vector<int> g_values; // single definition, visible to all TUs

Class-shared member (pre-C++17 requires an out-of-class definition; C++17+ allows inline static)

// MyClass.h
#include <vector>
class MyClass {
public:
    static std::vector<int> shared; // declaration
};

// MyClass.cpp
#include "MyClass.h"
std::vector<int> MyClass::shared; // definition

Function-local static (recommended to avoid initialization-order issues)

std::vector<int>& shared_vector() {
    static std::vector<int> instance;
    return instance;
}

Quick notes and troubleshooting: check you’re not reinitializing or assigning the vector in your constructor (that will overwrite shared storage). Beware the static initialization order across translation units — function-local statics avoid that. Since C++11, initialization of local statics is thread-safe. For testability and cleaner design, prefer passing a reference or injecting the shared container rather than sprinkling globals through the code.

Recommended Answers

All 3 Replies

No problem, I worked it out.

It seems that whenever I post on here I somehow manage to do it a couple minutes later having struggled previously for hours!!

I believe you meant how to create a static vector. If you want to make a class that will have a vector, which values won't change when creating instances of the class (namely objects) then use the static keyword.

class A{
static  vector v
}

Btw, try googling more next time with different kwywords. ;-) :)

Cheers :-)

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.