我发布了这个答案:https://stackoverflow.com/a/28459180/2642059其中包含以下代码:
void foo(string&& bar){
string* temp = &bar;
cout << *temp << " @:" << temp << endl;
}
Run Code Online (Sandbox Code Playgroud)
是bar左值还是左值?
我问,因为我显然不能取rvalue的地址,但我可以在这里完成rvalue引用的地址.
如果你可以对左值参考执行任何操作,你可以在左值参考上区分用"&&"而不仅仅是"&"来区分两者?
有这个代码:
#include <iostream>
class F {
public:
F() = default;
F(F&&) {
std::cout << "F(F&&)" << std::endl;
}
F(F&) {
std::cout << "F(F&)" << std::endl;
}
};
class G {
F f_;
public:
G(F&& f) : f_(f) {
std::cout << "G()" << std::endl;
}
};
int main(){
G g = F();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
F(F&)
G()
Run Code Online (Sandbox Code Playgroud)
为什么在类F(F&)的F(F&&)构造函数中调用构造函数而不是构造函数G?类的构造函数的参数G是F&& f它是右值引用但左值参考构造函数被调用.
我试图理解完美转发和构造函数的相互作用.我的例子如下:
#include <utility>
#include <iostream>
template<typename A, typename B>
using disable_if_same_or_derived =
std::enable_if_t<
!std::is_base_of<
A,
std::remove_reference_t<B>
>::value
>;
template<class T>
class wrapper {
public:
// perfect forwarding ctor in order not to copy or move if unnecessary
template<
class T0,
class = disable_if_same_or_derived<wrapper,T0> // do not use this instead of the copy ctor
> explicit
wrapper(T0&& x)
: x(std::forward<T0>(x))
{}
private:
T x;
};
class trace {
public:
trace() {}
trace(const trace&) { std::cout << "copy ctor\n"; }
trace& operator=(const …Run Code Online (Sandbox Code Playgroud)