2ちゃんねる スマホ用 ■掲示板に戻る■ 全部 1- 最新50    

■ このスレッドは過去ログ倉庫に格納されています

C++相談室 part162

143 :デフォルトの名無しさん :2022/11/16(水) 00:38:41.12 ID:g3O9ReAZM.net
>>142
template<typename T>
  T&& std::forward(typename remove_reference<T>::type& t) noexcept; //§35.5.1
template<typename T>
  T&& std::forward(typename remove_reference<T>::type&& t) noexcept;
template<typename TT, typename A>
unique_ptr<TT> make_unique(int i, A&& a)   // simple variant of make_shared (§34.3.2)
{
  return unique_ptr<TT>{new TT{i,forward<A>(a)}};
}

We want make_unique<T>(arg) to construct a T from an arg without making any spurious copies. To do that, it is essential that the lvalue/rvalue distinction is maintained. Consider: auto p1 = make_unique<Xref<string>>(7,"Here");

"Here" is an rvalue, so forward(string&&) is called, passing along an rvalue, so that Xref(int,string&&) is called to move from the string holding "Here". The more interesting (subtle) case is: auto p2 = make_unique<Xref<string>>(9,x); Here, x is an lvalue, so forward(string&) is called, passing along an lvalue: forward()’s T is deduced to string& so that the return value becomes string& &&, which means string& (§7.7.3). Thus, Xref(int,string&) is called for the lvalue x, so that x is copied.

Stroustrup, Bjarne. The C++ Programming Language (p.689). Pearson Education. Kindle 版.

総レス数 1001
307 KB
新着レスの表示

掲示板に戻る 全部 前100 次100 最新50
read.cgi ver 2014.07.20.01.SC 2014/07/20 D ★