我在下面给出一个例子。该程序编译并运行良好,但我想知道它是否是根据 C++11 标准理论上未定义的行为;我可以返回绑定(临时)本地函数对象的结果吗?
示例代码(简称编辑):
#include <iostream>
#include <functional>
struct MyFunctionObject
{
inline void operator() ( const std::string& name )
{ std::cout<< "Hello " << name << "!" << std::endl; }
};
std::function< void () > my_greeter( const std::string& name )
{
MyFunctionObject fun;
return std::bind( fun, name );
}
int main()
{
auto g = my_greeter("sheljohn");
g();
}
编辑原始示例:
#include <random>
#include <functional>
#include <algorithm>
#include <utility>
#include <iostream>
/******************** ********** ********************/
/******************** ********** ********************/
namespace foo {
/**
* Type of the generator returned by the method 'bind' below.
*/
template <class _dist>
using generator_type = std::function< typename _dist::result_type () >;
// ------------------------------------------------------------------------
/**
* Wrapper for C++11 random library.
*/
template <
class _engine = std::mt19937_64,
class _device = std::random_device
>
struct random
{
typedef _engine engine_type;
typedef _device device_type;
typedef random<_engine,_device> self;
template <class _dist>
static inline generator_type<_dist>
bind( _dist& distribution )
{ return std::bind( distribution, self::engine ); }
template <class _dist>
static inline generator_type<_dist>
bind( _dist&& distribution )
{ return std::bind( distribution, self::engine ); }
static engine_type engine;
static device_type device;
};
// Initialize static engine
template <class _engine,class _device>
_device random<_engine,_device>::device;
template <class _engine,class _device>
_engine random<_engine,_device>::engine = _engine( device() );
// ------------------------------------------------------------------------
/**
* Generic binder to standard random distributions.
*
* SO QUESTION: does this cause undefined behaviour?
*/
template <class _dist, class... Args>
constexpr generator_type<_dist> random_generator( Args&&... args )
{ return random<>::bind( _dist( std::forward<Args>(args)... ) ); }
}; // namespace: foo
/******************** ********** ********************/
/******************** ********** ********************/
int main()
{
auto ngen = foo::random_generator< std::normal_distribution<double> >( 0.0, 1.0 );
for(unsigned i=0; i<10; ++i)
std::cout<< ngen() << " " << std::endl;
}