相关疑难解决方法(0)

为什么可以将rvalue间接绑定到左值引用而不是直接绑定?

从我读过和看过的内容来看,你不能将一个rvalue的表达式绑定到左值引用.然而,我所看到的是你可以将rvalue绑定到rvalue引用,并且由于命名的rvalue引用本质上是一个左值,你可以将它绑定到左值引用.禁止将右值绑定到左值引用的原因是什么.它是出于优化目的吗?

举个例子:

#include <iostream>

using std::cout;

void bar ( int& b ) {

    cout << "bar " << b << "\n";
    b = 3;
}

void foo ( int&& a ) {

    cout << a << "\n";
    bar(a);
    cout << a << "\n";
}

int main ( int argc, char ** argv ) {

    foo(1);
}
Run Code Online (Sandbox Code Playgroud)

c++ c++11 c++14

10
推荐指数
2
解决办法
1723
查看次数

一个VS2010的bug?允许将非const引用绑定到rvalue而不发出警告?

string foo() { return "hello"; }
int main() 
{
    //below should be illegal for binding a non-const (lvalue) reference to a rvalue
    string& tem  = foo();   

    //below should be the correct one as only const reference can be bind to rvalue(most important const)
    const string& constTem = foo();   
}
Run Code Online (Sandbox Code Playgroud)
  1. GCC是一个很好的给出编译错误:std::string&从类型的临时类型无效初始化类型的非const引用std::string
  2. VS2008不算太差至少它给出了一个编译警告:警告C4239:初始化'::使用非标准扩展转换从std::stringstd::string &非const引用可以仅被绑定到一个左值
  3. 这有问题的一个 - VS2010(SP1)很好没有任何错误或警告,为什么?? !! 我知道VS2010中的rvalue引用可以用来绑定rvalue但是我没有使用&&,而是在演示代码中,我只是使用非const左值引用!

可以用somone帮我解释一下VS2010的行为吗?这是一个错误!?谢谢

c++ reference visual-studio-2010 rvalue lvalue

9
推荐指数
2
解决办法
2892
查看次数

为什么我在Linux上得到错误"没有用于调用A :: A(A)的匹配函数"但在Windows上没有

我编译时,以下代码在Linux上引发错误g++ test.cpp:

#include <iostream>

using namespace std;

class A
{
public:
    A(){
        cout << "call A()" << endl;
    };
    A& operator = (const A& a) {
        cout << "call operator =" << endl;
        return *this;
    }
    A(A& a) {
        cout << "call A(A& a)" << endl;
    }
};

A operator - (A& a1, A& a2)
{
    cout << "call operate -" << endl;
    return a1;
}

int main()
{
    A a1;
    A a2;
    A a3 = a1 - …
Run Code Online (Sandbox Code Playgroud)

c++ linux compiler-errors

1
推荐指数
1
解决办法
763
查看次数