Re: What's the proper way of initializing a std::function?
On 30 Apr., 15:31, DeMarcus <use_my_alias_h...@hotmail.com> wrote:
Daniel Kr?gler wrote:
On 29 Apr., 21:03, DeMarcus <use_my_alias_h...@hotmail.com> wrote:
[..]
In C++0x, is lambda the most proper way to initialize a std::function
with a valid function that does nothing?
class SomeClass
{
public:
SomeClass() : fnc_([]{}) {}
private:
std::function<void()> fnc_;
};
I'm not sure whether I understand your question correctly:
Is your requirement, that std::function should have a
target?
fnc_ may or may not be initialized with a proper function in a later
stage, i.e.
void setFnc( std::function<void()> fnc )
{
fnc_ = fnc;
}
I just want to be able to run fnc_() without a crash if it hasn't been
initialized by the user.
If you allow this assignment, you will probably need to verify
that the provided std::function object does contain a target,
otherwise you cannot give the guarantee you want to have,
depending on what you precisely mean with "crash", see
below.
1) If not, why is the default constructor not OK?
Will the default constructor guarantee me that I can call fnc_ without a
crash?
Depends on what you mean with "crash". std::function
will throw std::bad_function_call, if a target-free object
attempts to invoke the operator() overload.
User code would need to check for a target before
doing so. In fact, std::function is like a smart function
pointer, therefore it provides a built-in null state. Personally,
I never have seen the need to guarantee a non-null
std::function object, because user code is aware of
the optionality of the target (same as they are aware
of the optionality within a general std::auto_ptr or
boost::shared_ptr. This doesn't mean, that your
idea is insane, it just depends on your particular
use-case.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]