Singleton class implementation using shared_ptr - c++11

#include <iostream>
#include <memory>
using namespace std;
class Demo {
static shared_ptr<Demo> d;
Demo(){}
public:
static shared_ptr<Demo> getInstance(){
if(!d)
d.reset(new Demo);
return d;
}
~Demo(){
cout << "Object Destroyed " << endl;
}
};
// shared_ptr<Demo> Demo::d(new Demo); // private ctor is accepted
shared_ptr<Demo> Demo::d;
int main()
{
shared_ptr<Demo> d(Demo::getInstance());
cout << d.use_count() << endl;
return 0;
}
is this the correct way to implement the singleton class using shared_ptr
please see above commented line to initialize the static shared_ptr how come we can create an object here to initialize shared_ptr with a private construct

This is not thread-safe: two threads calling getInstance would cause a data race. A common approach is to use a function-scope static variable:
static shared_ptr<Demo> getInstance(){
static shared_ptr<Demo> d(new Demo);
return d;
}
Such a variable is guaranteed to be initialized exactly once, when control passes over its definition for the first time, and in a thread-safe manner.
At this point though, it's not at all clear why you would want to use shared_ptr. You could just as well do
static Demo& getInstance(){
static Demo d;
return d;
}
This is a textbook implementation of a singleton (well, one of).
Re: initialize with a private constructor. I'm not sure I understand the nature of your confusion. Are you asking why Demo::getInstance can use private constructor of Demo? Well, because it's a member of Demo, and members of a class can access private members of that class. Are you asking why Demo::getInstance can call shared_ptr<Demo>::reset() passing a Demo* pointer? Well, because reset() is a public member function of shared_ptr, taking a pointer as a parameter. Which part of this process do you find controversial?

My 2nd Question above is that how come private constructor called out side of class while instantiating the static member
// shared_ptr<Demo> Demo::d(new Demo); // private ctor is accepted
I think return local static wont work , see below example object destroyed twice
#include <iostream>
using namespace std;
class Demo {
public:
static Demo & getInstance(){
static Demo d;
return d;
}
~Demo(){
cout << "Demo destroyed" << endl;
}
};
void fun(){
Demo l = Demo::getInstance();
}
int main()
{
fun();
cout << "Hello World" << endl;
}

Some comments from 1 to help with the discussion. Static variable will be destroyed uppon exit of the application, so we don't need to use the smart pointer at this stage as mentioned above.
"If multiple threads attempt to initialize the same static local variable concurrently, the initialization occurs exactly once (similar behavior can be obtained for arbitrary functions with std::call_once).
Note: usual implementations of this feature use variants of the double-checked locking pattern, which reduces runtime overhead for already-initialized local statics to a single non-atomic boolean comparison.
(since C++11)
The destructor for a block-scope static variable is called at program exit, but only if the initialization took place successfully. "

Related

Encounter std::bad_weak_ptr exception after converting a unique_ptr created from a factory method to shared_ptr and using shared_from_this

In summary, I have a class inherited from std::enabled_shared_from_this, and there is a factory method return an std::unique_ptr of it. In another class, I convert the std::unique_ptr of the previous class object to std::shared_ptr, and then I call shared_from_this(), which then throws std::bad_weak_ptr. The code is shown below:
#include <memory>
#include <iostream>
struct Executor;
struct Executor1 {
Executor1(const std::shared_ptr<Executor>& executor,
int x): parent(executor) {
std::cout << x << std::endl;
}
std::shared_ptr<Executor> parent;
};
struct Backend {
virtual ~Backend() {}
virtual void run() = 0;
};
struct Executor: public Backend, public std::enable_shared_from_this<Executor> {
const int data = 10;
virtual void run() override {
Executor1 x(shared_from_this(), data);
}
};
// std::shared_ptr<Backend> createBackend() {
std::unique_ptr<Backend> createBackend() {
return std::make_unique<Executor>();
}
class MainInstance {
private:
std::shared_ptr<Backend> backend;
public:
MainInstance(): backend(createBackend()) {
backend->run();
}
};
int main() {
MainInstance m;
return 0;
}
Indeed changing std::unique_ptr<Backend> createBackend() to std::shared_ptr<Backend> createBackend() can solve the problem, but as I understand, in general, the factory pattern should prefer return a unique_ptr. Considering a good pratice of software engineering, is there a better solution?
[util.smartptr.shared.const]/1 In the constructor definitions below, enables shared_from_this with p, for a pointer p of type Y*, means that if Y has an unambiguous and accessible base class that is a specialization of enable_shared_from_this (23.11.2.5), then [magic happens that makes shared_from_this() work for *p - IT]
template <class Y, class D> shared_ptr(unique_ptr<Y, D>&& r);
[util.smartptr.shared.const]/29 Effects: ... equivalent to shared_ptr(r.release(), r.get_deleter())...
template<class Y, class D> shared_ptr(Y* p, D d);
[util.smartptr.shared.const]/10 Effects: ... enable shared_from_this with p
Your example executes std::shared_ptr<Backend>(uptr) where uptr is std::unique_ptr<Backend>, which is equivalent to std::shared_ptr<Backend>(p, d) where p is of type Backend*. This constructor enables shared_from_this with p - but that's a no-op, as Backend doesn't have an unambiguous and accessible base class that is a specialization of enable_shared_from_this
In order for Executor::enable_from_this to work, you need to pass to a shared_ptr constructor a pointer whose static type is Executor* (or some type derived therefrom).
Ok, I find a simple solution, that is, using auto as the return type of the factory function, instead of std::unique_ptr or std::shared_ptr, and keeping std::make_unique inside the factory function. The factory function createBackend should be:
auto createBackend() {
return std::make_unique<Executor>();
}
In this case, the return type can be automatically determined, although I don't know how it works exactly. This code can return either unique_ptr or shared_ptr, which should be better than just using shared_ptr. I tested clang and gcc, and both of them worked, but I am still not sure if this is gauranteed by the type deduction and the implicit conversion.
Update:
Actually, I have found that auto deduces the return type above as std::unique_ptr<Executor> instead of std::unique_ptr<Backend>, which might be the reason why the code works. But using auto has an issue: if you return the smart pointer in an if-else block, where the return type varies depending on some parameters, then auto cannot determine the type. For example:
std::unique_ptr<Backend> createBackend(int k = 0) {
if (k == 0) {
return std::make_unique<Executor>();
}
else {
return std::make_unique<Intepreter>();
}
}
Here, both Executor and Intepreter derive from Backend. I think a correct solution includes:
Inherit Backend instead of its derived classes from std::enable_shared_from_this;
Use dynamic_pointer_cast<Derived class> to cast the shared_ptr to derived class after shared_from_this.
The full code is listed in:
https://gist.github.com/HanatoK/8d91a8ed71271e526d9becac0b20f758

std::function and friend function

In this example, I have a pointer of function (std::function) as an attribute of my class. So I can associate any function of the form void myFunction(void) to my class.
#include <iostream>
#include <functional>
class Example{
private:
int variable=4;
public:
std::function<void(void)> myNonMemberFunction;
Example(void){
}
Example(std::function<void(void)> MyNonMemberFunction){
myNonMemberFunction=MyNonMemberFunction;
}
};
void PrintPlop(){
std::cout<<"plop"<<std::endl;
}
int main() {
Example example(PrintPlop);
example.myNonMemberFunction();
}
Now, I want to do the same but with a function which has accessed to the class attribute like a friend function or a class-member function. How can I do this?
So you want any function you pass to the constructor become a friend?
In the strict sense it is impossible, because the access level (friend or not) is a compile-time issue, and which value is passed to the constructor, generally speaking, is determined only in run-time.
So you either declare all the relevant functions as friends (why not just make them methods in this case?) or pass the private members to them as additional parameters. Like this:
class Example{
private:
int variable=4;
std::function<void(int)> myNonMemberFunction;
public:
Example(void){
}
Example(std::function<void(int)> MyNonMemberFunction){
myNonMemberFunction=MyNonMemberFunction;
}
void callMyNonMemberFunction() {
myNonMemberFunction(variable);
}
};
void PrintPlop(int v){
std::cout<<"plop"<< v << std::endl;
}
int main() {
Example example(PrintPlop);
example.callMyNonMemberFunction();
}

C++ 11 passing shared_pointer like with std::any

at the moment I'm facing following problem. I need a member function in a derived class that can handle different shared_ptr types and do custom stuff with it. The base class should make sure that such a member function is implemented but the specific shared_ptr types are only known when a other developer create a new derived class. Therefore, templates are not a solution due to the fact that c++ not support virtual template functions.
The shared_ptrs hold protobuf message specific publisher or subscriber. Here a snipped of code:
std::shared_ptr<Publisher<ProtobufMessageType1>> type1 = std::make_shared<ProtobufMessageType1>();
std::shared_ptr<Publisher<ProtobufMessageType2>> type2 = std::make_shared<ProtobufMessageType2>();
class derived : base
{
void takeThePointerAndDoSpecificStuff( std::shared_ptr<PubOrSub<SpecificProtobufMessage>>) override
{
// check type and bind specific callback
}
}
One solution could be casting shared_ptr to base class but it is not possible because the protobuf message base class is pure virtual. Another solution is to cast the raw pointer and only transfer this one but I need the share_ptr reference count also in the method ( due to binding).
So I look further for a solution and std::any could be one but the problem here is that c++11 not have a std::any (sure could use boost but I try to avoid that).
So now I'm out of ideas how to solve the problem but perhaps you have one and can help me.
Thank you for any answer in advance.
One solution could be casting shared_ptr to base class but it is not possible because the protobuf message base class is pure virtual
That's simply not true. You can have shared pointers to abstract bases just fine:
Live On Coliru
#include <memory>
#include <iostream>
struct Base {
virtual ~Base() = default;
virtual void foo() const = 0;
};
struct D1 : Base { virtual void foo() const override { std::cout << __PRETTY_FUNCTION__ << "\n"; } };
struct D2 : Base { virtual void foo() const override { std::cout << __PRETTY_FUNCTION__ << "\n"; } };
int main() {
std::shared_ptr<Base> b = std::make_shared<D1>();
std::shared_ptr<Base> c = std::make_shared<D2>();
b->foo();
c->foo();
}
Prints
virtual void D1::foo() const
virtual void D2::foo() const
More Ideas
Even in case you do not have a common base (or a base at all) you can still use shared_pointer. One particularly powerful idiom is to use shared_pointer<void>:
Live On Coliru
#include <memory>
#include <iostream>
struct D1 {
void foo() const { std::cout << __PRETTY_FUNCTION__ << "\n"; }
~D1() { std::cout << __PRETTY_FUNCTION__ << "\n"; }
};
struct D2 {
void bar() const { std::cout << __PRETTY_FUNCTION__ << "\n"; }
~D2() { std::cout << __PRETTY_FUNCTION__ << "\n"; }
};
int main() {
std::shared_ptr<void> b = std::make_shared<D1>();
std::shared_ptr<void> c = std::make_shared<D2>();
std::static_pointer_cast<D1>(b)->foo();
std::static_pointer_cast<D2>(c)->bar();
}
Prints
void D1::foo() const
void D2::bar() const
D2::~D2()
D1::~D1()
See: http://www.boost.org/doc/libs/1_66_0/libs/smart_ptr/doc/html/smart_ptr.html#techniques_using_shared_ptr_void_to_hold_an_arbitrary_object

C++11 move assignment operator for classes with objects as members - Beginner Level

I have a beginner question on the move assigment in c++11. Let say that I have a class A provided with a move assigment operator:
class A
{
public:
A();
~A();
A& operator=(A&&);
...
}
I also have a class B containing a class A object and provided with a move assignment operator
class B
{
public:
B();
~B();
B& operator=(B&&);
...
private:
A Test;
}
What I was thinking is that the B move assignment operator will call the move assignment operator of its member so I tried this method:
B& B::operator=(B&& Other)
{
...
Test = Other.Test;
...
return *this;
}
But this is not working since the move assignment of class A is not called.
Instead I was able to make the program work by using this method:
B& B::operator=(B&& Other)
{
...
Test = std::move(Other.Test);
...
return *this;
}
I do not understand why the first method is not working. I was thinking that since a constructor will call its members constructors the move assignment operator should do the same. Am I wrong or I made a mistake in my code? Can someone explain, thanks!
Other.Test is not an rvalue expression since it has a name. OTOH std::move(Other.Test) has the type A and the value category xvalue (i.e., an rvalue). Thus, it can bind to the move constructor.
(EDIT : Shamelessly copied #dyp's comment. Thanks, #dyp and #KerrekSB.)
#Pradhan is correct - you need to use std::move to move the members in the implementation of the move assignment operator. However, if that is all that is needed to implement your move constructor, then you can declare the operator to use the default implementation:
#include <memory>
class A {
public:
A() : p{} { }
~A() { }
A &operator=(A &&) = default;
// Instead of:
// A &operator=(A &&other) {
// p = std::move(other.p);
// return *this;
// }
private:
std::unique_ptr<int> p;
};
int main() {
A a;
A b;
b = std::move(a);
return 0;
}

invalid use of non-static data member from a lambda expression [duplicate]

I really like the idea of properties in C#, and as a little side project, I've been tinkering with the idea of implementing them in C++. I ran into this example https://stackoverflow.com/a/5924594/245869 which seems fairly nice, but I couldn't help but think that lambdas and non-static data member initialization may make it possible to use some very nice syntax with this idea. Here's my implementation:
#include <iostream>
#include <functional>
using namespace std;
template< typename T >
class property {
public:
property(function<const T&(void)> getter, function<void(const T&)> setter)
: getter_(getter),
setter_(setter)
{};
operator const T&() {
return getter_();
};
property<T>& operator=(const T& value) {
setter_(value);
}
private:
function<const T&(void)> getter_;
function<void(const T&)> setter_;
};
class Foobar {
public:
property<int> num {
[&]() { return num_; },
[&](const int& value) { num_ = value; }
};
private:
int num_;
};
int main() {
// This version works fine...
int myNum;
property<int> num = property<int>(
[&]() { return myNum; },
[&](const int& value) { myNum = value; }
);
num = 5;
cout << num << endl; // Outputs 5
cout << myNum << endl; // Outputs 5 again.
// This is what I would like to see work, if the property
// member of Foobar would compile...
// Foobar foo;
// foo.num = 5;
// cout << foo.num << endl;
return 0;
}
I can use my property class normally [see the example in main()], but MinGW with g++4.7 doesn't particularly care for my attempt at using the property as a data member:
\property.cpp: In lambda function:
\property.cpp:40:7: error: invalid use of non-static data member 'Foobar::num_'
So it seems the concept of my property implementation works, but it might be in vain because I can't access other data members from my lambda functions. I'm not sure how the standard defines what I'm trying to do here, am I completely out of luck, or am I just not doing something right here?
Your property is a different object (instance of property<int>) from the containing object (instance of Foobar). As such, its member functions get passed a different this, not the one you'd need to access num_ -- so you can't do it that way. If the lambdas were defined in a non-static member function of Foobar, they would have captured that function's this argument and would have had access to the enclosing object's members (explicitly, as this->num_). But the lambdas are defined in the class, where the non-static data members don't actually exist. If the lambdas did have access to num_, which num_, of which instance of Foobar, would have been that?
The easiest solution that I see is for the property to store a pointer to the enclosing object. That way, it can freely access its non-static members. The downside is that the declaration is slightly more complex (you'd have to do property<int, Foobar> num) and you'd need to initialize the property by passing the this pointer. So you won't be able to do it in the class, it would have to be in the constructor's initialization list, hence negating the advantage of C++11's data member initialization.
At that point, this would be available to the lambdas to capture anyway (by value, not by reference!) so your code would actually work with minimal changes, if you moved the initialization of the property to Foobar's constructor(s):
Foobar::Foobar():
num {
[this]() { return this->num_; },
[this](const int& value) { this->num_ = value; }
}
{
}
Does anyone know whether this, as passed to whatever constructor happens to be invoked, is available for non-static member initialization in the class definition? I suspect it isn't, but if it were, the same construction would work inside the class definition.

Resources