diff --git a/v2_0_cpp_adaptor.md b/v2_0_cpp_adaptor.md index 7c81cc2..17705f4 100644 --- a/v2_0_cpp_adaptor.md +++ b/v2_0_cpp_adaptor.md @@ -282,6 +282,45 @@ struct object_with_zone { https://github.com/msgpack/msgpack-c/blob/master/example/cpp03/class_non_intrusive.cpp +When you use `msgpack::object::as` member function template in `convert` class template specilization, , temporary objects are created. + +```C++ +template<> +struct convert { + msgpack::object const& operator()(msgpack::object const& o, my_class& v) const { + if (o.type != msgpack::type::ARRAY) throw msgpack::type_error(); + if (o.via.array.size != 2) throw msgpack::type_error(); + v = my_class( + o.via.array.ptr[0].as(), // temporary object is created here + o.via.array.ptr[1].as()); + return o; + } +}; +``` + +If you can get the reference of the member variables in converting target class, you can remove the temporary object creation. For example, if member variables of `my_class` are public, you can apply `operator>>` to them as follows: + +```C++ +class my_class { +public: + /* ... */ + std::string name_; + int age_; +}; + +template<> +struct convert { + msgpack::object const& operator()(msgpack::object const& o, my_class& v) const { + if (o.type != msgpack::type::ARRAY) throw msgpack::type_error(); + if (o.via.array.size != 2) throw msgpack::type_error(); + o.via.array.ptr[0] >> v.name_; // no temporary object creation + o.via.array.ptr[1] >> v.age_; + return o; + } +}; +``` + + #### non default constructible class support (C++11 only, since 1.2.0) You might want to convert to a class that doesn't have default constructor from a msgpack::object. In order to do that, you can use 'as' class template specialization.