Re: some problem about move semantics

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



在 2019-03-25一的 09:32 +0800,叶佑群写道:
> Hi,all, I have code as below:
> 
> void check(int & val)
> {
> 	std::cout << "int &\n";
> }
> 
> void check(int && val)
> {
> 	std::cout << "int &&\n";
> }
> 
> template <typename T>
> void print (T && val)
> {
> 	check (std::forward<T>(val));
> }
> 
> int main()
> {
> 	int x = 0;
> 	print (x);
> 	print (std::move (x));
> }
> 
> I have some problems:
> 
> A、when call print (std::move (x)), the compiler will deduction print to
> 	Void print (int && val)
> 	
> 	So val is a rvalue reference, so check (int && val) should be
> invoked, but actually not, why? Function forward just do a static_cast here,
> its result also make val a rvalue reference?

I can not understand your problem so I'll just explain what is happening.

When you call "print(std::move(x))", "T" is deducted to be "int".  When you call
"print(x)", "T" is deducted to be "int &".  So "T &&" is "int &" (reference
collapsing).  Let's instantiate them:

void print<int>(int &&val)
{
  check(std::forward<int>(val));
}

void print<int &>(int &val)
{
  check(std::forward<int &>(val));
}

std::forward is defined as-is:

template <class T> constexpr T&& forward(remove_reference_t<T>& t) noexcept
{
  return static_cast<T&&>(t);
}

template <class T> constexpr T&& forward(remove_reference_t<T>&& t) noexcept
{
  return static_cast<T&&>(t);
}

In print<int> it will be instantiated:

constexpr int&& forward<int>(remove_reference_t<int>&& t) noexcept
{
  return static_cast<int&&>(t);
}

In print<int&>, reference collapsing happens again since "T" is "int &", so
"T&&" is "int &":

constexpr int& forward<int&>(remove_reference_t<int&>& t) noexcept
{
  return static_cast<int&>(t);
}
-- 
Xi Ruoyao <xry111@xxxxxxxxxxxxxxxx>
School of Aerospace Science and Technology, Xidian University




[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux