why is it necessary that this code calls std::forward<>?

Hi,

I have this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
	int retInt()
	{
		return 6;
	}

	template<typename T>
	auto f(T&& val)
	{
		using rawVal = std::decay<T>::type;
		rawVal* tmp = new rawVal{ std::forward<T>(val) };
		return tmp;
	}

	void use()
	{
		int vec[5] {1,2,3,4,5};
		auto a = f(vec);
		auto b = f(5);
		auto c = f(retInt);
        }


why do I need to call std::forward?

Thanks
Last edited on
You don't need to, it does nothing for this example. It would do something useful if you had a call with a T that has a move constructor, e.g.

auto d = f( std::vector{1,2,3,4,5} );
(in that case, new rawVal{ val }; would make a copy of the vector, while new rawVal{ std::forward<T>(val) } would move it)

Also, gratuitous memory leaks are gross.
Topic archived. No new replies allowed.