min算法通常表示如下:
template <typename T>
const T& min(const T& x, const T& y)
{
return y < x ? y : x;
}
Run Code Online (Sandbox Code Playgroud)
但是,这不允许表单的构造min(a, b) = 0.您可以通过额外的重载实现这一目标:
template <typename T>
T& min(T& x, T& y)
{
return y < x ? y : x;
}
Run Code Online (Sandbox Code Playgroud)
我想做的是通过完美转发统一这两个重载:
template <typename T>
T&& min(T&& x, T&& y)
{
return y < x ? std::forward<T>(y) : std::forward<T>(x);
}
Run Code Online (Sandbox Code Playgroud)
但是,g ++ 4.5.0会发出警告,min(2, 4)表示我返回对临时的引用.我做错什么了吗?
好的,我明白了.问题在于条件运算符.在我的第一个解决方案中,如果我调用min(2, 4)条件运算符,则会看到xvalue,从而从转发中移动x以生成临时对象.当然,通过引用返回它是危险的!如果我转了整个表达,而不是x和y …
我想Foo从函数返回一个不可复制的类型对象.这基本上是一个辅助对象,调用者将使用它来执行一组操作,析构函数在操作完成后执行一些清理.
在rvalue引用出现之前,我会返回一个shared_ptr<Foo>或类似的东西.使用rvalue引用,另一个选项是使构造函数和复制构造函数成为私有,并使唯一的公共构造函数成为移动构造函数.Foo看起来像这样:
class Foo : boost::noncopyable
{
private:
Foo( /* whatever the real ctor needs */ );
public:
Foo( Foo && src );
// ... interesting stuff ...
};
Foo a( SomethingThatReturnsFoo() ); // allowed
Foo b; // error, no public default constructor
Foo c( a ); // error, noncopyable
Foo d = a; // error, noncopyable
Run Code Online (Sandbox Code Playgroud)
我的问题是,这样做是否不好,或者看起来是否合理.我想不出有什么理由会导致问题或者难以阅读,但是当涉及到rvalue引用时,我仍然是一个新手,所以可能会考虑我没想到的.
考虑以下代码:
#include <iostream>
void f(int&& i)
{
std::cout << "f(int&&)\n";
}
void f(const int&& i)
{
std::cout << "f(const int&&)\n";
}
int fun_i()
{
return 0;
}
const int fun_ci()
{
return 0;
}
int main()
{
f(fun_i());
f(fun_ci());
}
Run Code Online (Sandbox Code Playgroud)
如果我用MSVC 2012编译它,输出是:
f(int&&)
f(const int&&)
Run Code Online (Sandbox Code Playgroud)
如果我用GCC 4.7编译,输出是:
f(int&&)
f(int&&)
Run Code Online (Sandbox Code Playgroud)
哪个是对的?
(如果我删除f的第二个定义,程序将无法在MSVC 2012下编译,但它确实在GCC 4.7下编译.)
请考虑以下代码:
struct MyString
{
// some ctors
MyString& operator+=( const MyString& other ); // implemented correctly
};
MyString operator+( const MyString& lhs, const MyString& rhs )
{
MyString nrv( lhs );
nrv += rhs;
return nrv;
}
MyString&& operator+( MyString&& lhs, const MyString& rhs )
{
lhs += rhs;
return std::move( lhs ); // return the rvalue reference we received as a parameter!
}
Run Code Online (Sandbox Code Playgroud)
这适用于以下用例
MyString a, b, c; // initialized properly
MyString result = a + b + c; …Run Code Online (Sandbox Code Playgroud) 假设我有字符串向量,我想通过std :: accumulate连接它们.
如果我使用以下代码:
std::vector<std::string> foo{"foo","bar"};
string res="";
res=std::accumulate(foo.begin(),foo.end(),res,
[](string &rs,string &arg){ return rs+arg; });
Run Code Online (Sandbox Code Playgroud)
我可以肯定会有临时对象构造.
在这个答案中,他们说std :: accumulate的效果是这样指定的:
通过初始化累加器acc初始值init计算其结果,然后按顺序对[= first,last]范围内的每个迭代器i用acc = acc +*i或acc = binary_op(acc,*i)修改它.
所以我想知道这样做的正确方法是什么,以避免不必要的临时对象构造.
一个想法是以这种方式改变lambda:
[](string &rs,string &arg){ rs+=arg; return rs; }
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我认为我强制有效串联字符串并帮助编译器(我知道我不应该)省略不必要的副本,因为这应该等同于(伪代码):
accum = [](& accum,& arg){ ...; return accum; }
Run Code Online (Sandbox Code Playgroud)
因此
accum = & accum;
Run Code Online (Sandbox Code Playgroud)
另一个想法是使用
accum = [](& accum,& arg){ ...; return std::move(accum); }
Run Code Online (Sandbox Code Playgroud)
但这可能会导致类似于:
accum = std::move(& accum);
Run Code Online (Sandbox Code Playgroud)
这看起来很可疑.
写这个的正确方法是什么,以尽量减少不必要的临时对象创建的风险?我不仅对std :: string感兴趣,我很乐意有一个解决方案,这可能适用于任何具有复制和移动构造函数/赋值的对象.
#include <vector>
using namespace std;
struct A
{
A(const vector<int>&) {}
A(vector<int>&&) {}
};
A f()
{
vector<int> coll;
return A{ coll }; // Which constructor of A will be called as per C++11?
}
int main()
{
f();
}
Run Code Online (Sandbox Code Playgroud)
是coll一个xvalue在return A{ coll };?
返回A(vector<int>&&)时是否会调用C++ 11保证f?
std::optional::value() 有两个以上的重载
constexpr T& value() &;
constexpr const T & value() const &;
constexpr T&& value() &&;
constexpr const T&& value() const &&;
Run Code Online (Sandbox Code Playgroud)
返回const右值引用有什么意义?
我能想到的唯一原因是使编译器能够帮助捕获未完成的行为(真的很奇怪),如下所示
auto r = std::cref(const_cast<const std::optional<int>&&>(
std::optional<int>{}).value());
Run Code Online (Sandbox Code Playgroud)
如果std::optional::value()已返回a,const T&则上述代码将编译,并在r reference_wrapper以后使用时导致未定义的行为.
以上返回的是否有任何其他角落案例const T&&?
为什么我们不能同时实现的方法getAB() &&和getAB(),但可以实现其中任何一个?
码:
struct Beta {
Beta_ab ab;
Beta_ab && getAB() && { cout << "1"; return move(ab); }
};
int main() {
Beta_ab ab = Beta().getAB();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
码:
struct Beta {
Beta_ab ab;
Beta_ab && getAB() { cout << "2"; return move(ab); }
};
int main() {
Beta b;
Beta_ab ab = b.getAB();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
码:
struct Beta { …Run Code Online (Sandbox Code Playgroud) 以下代码:
#include <tuple>
int main ()
{
auto f = [] () -> decltype (auto)
{
return std::get<0> (std::make_tuple (0));
};
return f ();
}
Run Code Online (Sandbox Code Playgroud)
(静默地)生成具有未定义行为的代码 - 返回的临时rvalue make_tuple通过std :: get <>和decltype(auto)传播到返回类型.因此它最终返回对超出范围的临时引用.请在此处查看https://godbolt.org/g/X1UhSw.
现在,你可以说我的使用decltype(auto)是错误的.但是在我的通用代码中(元组的类型可能是std::tuple<Foo &>),我不想总是复制.我真的想从元组中提取确切的值或引用.
我的感觉是这种超载std::get是危险的:
template< std::size_t I, class... Types >
constexpr std::tuple_element_t<I, tuple<Types...> >&&
get( tuple<Types...>&& t ) noexcept;
Run Code Online (Sandbox Code Playgroud)
虽然将左值引用传播到元组元素可能是明智的,但我认为这不适用于右值引用.
我确信标准委员会非常仔细地考虑了这一点,但任何人都可以向我解释为什么这被认为是最佳选择?
我TTempTable上课有移动共鸣。我写
TTempTable&& MyFunction() {
TTempTable tmp = f(...);
...
return std::move(tmp);
}
Run Code Online (Sandbox Code Playgroud)
并且没有编译器错误。
这是正确的吗?
c++ ×10
rvalue-reference ×10
c++11 ×8
c++14 ×2
accumulate ×1
algorithm ×1
c++17 ×1
forwarding ×1
return-value ×1
rvo ×1
stdoptional ×1
stdtuple ×1
templates ×1