Joh*_*hnB 11 c++ rvalue-reference c++11
考虑到(x | r | l | pr | gl)值,我想到了以下问题:
考虑以下两个变量声明:
X x = ...;
Run Code Online (Sandbox Code Playgroud)
和
X&& x = ...;
Run Code Online (Sandbox Code Playgroud)
并承担了...做不提供的x值.
任何人都可以想到代码没有使用decltype,这会产生什么影响?在这两种情况下,(x)都会通过左值型X,不是吗?
也许人为的例子,但有
struct X
{
X() = default;
X(const X&) = delete;
X operator =(const X&) = delete;
X(X&&) = delete;
X operator =(X&&) = delete;
};
X makeX() {return {};}
Run Code Online (Sandbox Code Playgroud)
以下编译
X&& x = makeX();
Run Code Online (Sandbox Code Playgroud)
而后续则没有
X x = makeX();
Run Code Online (Sandbox Code Playgroud)
模板非类型参数不能引用临时. 因此,给定
struct X {};
X purr() { return {}; }
X x1 = purr();
X&& x2 = purr();
template<X&> class woof {};
Run Code Online (Sandbox Code Playgroud)
我们有
woof<x1> w1; // OK
woof<x2> w2; // Error
Run Code Online (Sandbox Code Playgroud)
如果...不限于类型的纯右值X,那么切片是一种使两者不等价的不太晦涩的方法。鉴于:
struct X { virtual ~X() = default; };
struct Y : X {};
Y meow() { return {}; }
Run Code Online (Sandbox Code Playgroud)
然后:
X x1 = meow(); // slices
X&& x2 = meow(); // doesn't slice
Run Code Online (Sandbox Code Playgroud)
因此:
dynamic_cast<Y&>(x1); // throws std::bad_cast
dynamic_cast<Y&>(x2); // OK
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
385 次 |
| 最近记录: |