简体   繁体   English

将按引用传递和按值传递混合到可变参数模板函数是否有效?

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

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. 例如,使用带有一些by-value和一些by-reference的构造函数分配一个类。 It compiles, but I'm not sure if it has any nasty side-effects or not. 它编译,但我不确定它是否有任何令人讨厌的副作用。

What you're looking for is perfect forwarding , ie. 您正在寻找的是完美的转发 ,即。 your AllocateObject function should be completely transparent as far as copying side effects are concerned. 就复制副作用而言,您的AllocateObject函数应该是完全透明的。

This involves both std::forward (as nijansen already mentioned) and the use of universal references in your parameter list: 这涉及std::forward (如已提到的nijansen)和参数列表中通用引用的使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM