Reputation: 399
I'm learning C++ and I'm trying to implement a Singleton. Here's the code:
#include <string>
#include <iostream>
class Configuration{
Configuration(){
languageName = "English";
};
public:
std::string languageName;
static Configuration& instance(){
static Configuration _instance;
return _instance;
}
};
int main(){
auto config = Configuration::instance();
config.languageName = "Deutsch";
std::cout<<config.languageName<<std::endl;//Deutsch
auto config2 = Configuration::instance();
std::cout<<config.languageName<<std::endl;//Deutsch
std::cout<<config2.languageName<<std::endl;//English
std::cout<<(&config == &config2)<<std::endl;//0
}
I expected that if I set the value of language on one instance, the same value will be held by a second instance since both instances are in fact the same.
But in the above code config2
and config
have different values for languageName
. What is the reason for this? I'm following the code from a tutorial.
Upvotes: 1
Views: 174
Reputation: 172994
both instances are in fact the same
No, they're not the same instance. Even Configuration::instance()
returns reference, the variables in main()
are not declared as reference too, so the returned reference will be copied. You need to declare them to be reference to avoid copying. Such as,
auto& config = Configuration::instance();
~
auto& config2 = Configuration::instance();
~
BTW: To ensure there's only one instance, you might want to delete
the copy/move constructor and assignment operator.
Upvotes: 2