How to pass default parameter for std :: shared_ptr <PureVirtualClass>

I have a function like

virtual void foo(bla, bla, bla, std::shared_ptr<LoggerInterface> logger) = 0; 

And I want to pass the default parameter with a NULL pointer, for example:

 virtual void foo(bla, bla, bla, std::shared_ptr<LoggerInterface> logger = NULL) = 0; 

So in the implementation, if logger is NULL , I do nothing with it, otherwise I use a logger.

I tried to find a solution, but I can not find.

UPD: the repeated requirement does not matter, I ask about the default NULL parameter.

Is it possible that gcc 4.4 does not support nullptr?

+5
source share
2 answers

You can simply do this:

 virtual void foo(bla, bla, bla, std::shared_ptr<LoggerInterface> logger = {}) = 0; 

As you can see here , both the empty constructor and nullptr give the same result, nullptr .:

Creates shared_ptr without a managed object, i.e. empty shared_ptr

+2
source

With compiler compatible with C ++ 11

This should work with either NULL or nullptr , which is the recommended form for C ++. The only condition is that you compile it for C ++ 11 or higher (see jamek's comment on command line options for gcc).

 struct B { virtual void foo(int blablabla, std::shared_ptr<LoggerInterface> logger = nullptr) = 0; }; struct D : B { void foo(int blablabla, std::shared_ptr<LoggerInterface> logger) override { std::cout << "foo: "<<blablabla<<" "<< logger<<std::endl; } }; int main() { D d; B *b=&d; b->foo(15); } 

Watch the online demo

Important Note on Default Settings

Please note that the default parameter is not an integral part of the function itself, but the context in which the default value is declared. In the above example:

  • b->foo(15) works because the function is accessed using class B , for which the default parameter is set.
  • d.foo(15) doesn't even compile even though they reference the same function. This is because for class D I did not declare a default value in the override definition.
  • I could have a different default value for both definitions (see online demo)

Limited implementation of C ++ 11 in GCC 4.4

Indeed, nullptr was introduced with GCC 4.6, and you should wait for GCC 4.8.1 to fully implement C ++ 11 ,

In fact, GCC 4.4.0 was released in 2009 and the first subclause after the standard was officially approved in August 2011 was GCC 4.4.7.

+1
source

Source: https://habr.com/ru/post/1262034/


All Articles