C++ Review Questions

Pages: 1... 8910
That worked thanks!

But if someone wanted to hide their code & keep them separate? I suppose it would work just find in modules as they are kept together, but I am not ready to delve into modules just yet.

What is everyone else using as an alternative to singleton's, unique_ptr?
I have never had the need for a pure singleton. Ive had plenty of classes where I only created one object from it, but actively preventing making more just never seemed useful. Ive also had static data classes where making a second one was just a copy of the first in a new scope, granting access to basically global variables, which is more or less the same idea but without the one instance locker or funky pointer accessors etc.


There are rare situations where a singleton class-object is actually required.
Otherwise, I tend to use a namespace.

For example:

#include <string>
#include <vector>
#include <algorithm>

president_name.h
1
2
3
4
5
6
7
namespace president_name
{
    extern const std::string& current ;
    extern const std::vector<std::string>& former ;

    bool add_former( std::string name ) ;
}


president_name.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
namespace president_name
{
    namespace
    {
        std::string current_ = "Biden" ;
        std::vector<std::string> former_ { "Trump", "Obama" } ;
    }

    const std::string& current = current_ ;
    const std::vector<std::string>& former = former_ ;

    bool add_former( std::string name )
    {
        // if duplicate, return false ;
        former_.push_back( std::move(name) ) ;
        return true ;
    }
}


Usage:
1
2
3
4
president_name::add_former( "Nixon" ) ;
std::cout << president_name::current << " *\n" ;
for( const std::string& name : president_name::former ) std::cout << name << '\n' ;
// etc. 

Topic archived. No new replies allowed.
Pages: 1... 8910