将按引用传递和按值传递混合到可变参数模板函数有效吗? [英] Mixing pass-by-reference and pass-by-value to variadic template function valid?

查看:44
本文介绍了将按引用传递和按值传递混合到可变参数模板函数有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个为对象分配内存,然后调用其构造函数的方法-内存分配器.

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.

推荐答案

您正在寻找的是完美转发,即.就复制副作用而言,您的 AllocateObject 函数应该完全透明.

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

这涉及到 std :: forward (如nijansen所述)和参数列表中通用引用的使用:

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
}

这篇关于将按引用传递和按值传递混合到可变参数模板函数有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆