Mixing pass-by-reference and pass-by-value to variadic template function valid?

此生再无相见时 提交于 2021-02-08 14:11:27

问题


I have a method which allocates memory for a object and then calls its constructor - a memory allocator.

template <class T, typename... Arguments>
inline T* AllocateObject(Arguments... args) { return new (InternalAllocate(sizeof(T))) T(args...); }

Is it valid using this function to mix pass-by-value and pass-by-reference? For example allocating a class with a constructor with some by-value and some by-reference. It compiles, but I'm not sure if it has any nasty side-effects or not.


回答1:


What you're looking for is perfect forwarding, ie. your AllocateObject function should be completely transparent as far as copying side effects are concerned.

This involves both std::forward (as nijansen already mentioned) and the use of universal references in your parameter list:

template <class T, typename... Arguments>
inline T* AllocateObject(Arguments&&... args)
//                                ^^ universal references
{
    return new (InternalAllocate(sizeof(T))) T(std::forward<Arguments>(args)...);
    //                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ forwarding
}


来源:https://stackoverflow.com/questions/19444159/mixing-pass-by-reference-and-pass-by-value-to-variadic-template-function-valid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!