相关疑难解决方法(0)

为什么非const引用不能绑定到临时对象?

为什么不允许对一个临时对象进行非const引用,哪个函数getx()返回?显然,这是C++标准禁止的,但我对这种限制的目的感兴趣,而不是对标准的引用.

struct X
{
    X& ref() { return *this; }
};

X getx() { return X();}

void g(X & x) {}    

int f()
{
    const X& x = getx(); // OK
    X& x = getx(); // error
    X& x = getx().ref(); // OK
    g(getx()); //error
    g(getx().ref()); //OK
    return 0;
}
Run Code Online (Sandbox Code Playgroud)
  1. 很明显,对象的生命周期不是原因,因为C++标准不禁止对对象的持续引用.
  2. 很明显,上面的示例中的临时对象不是常量,因为允许调用非常量函数.例如,ref()可以修改临时对象.
  3. 此外,ref()允许您欺骗编译器并获取此临时对象的链接,这解决了我们的问题.

此外:

他们说"为const引用分配一个临时对象可以延长这个对象的生命周期","但是对于非const引用却没有任何说法".我的其他问题.以下赋值是否延长了临时对象的生命周期?

X& x = getx().ref(); // OK
Run Code Online (Sandbox Code Playgroud)

c++ const reference temporary c++-faq

221
推荐指数
6
解决办法
9万
查看次数

为什么copy-constructor参数为const?

 Vector(const Vector& other) // Copy constructor 
 {
    x = other.x;
    y = other.y;
Run Code Online (Sandbox Code Playgroud)

为什么参数是const?

c++ constructor

28
推荐指数
2
解决办法
2万
查看次数

隐式转换和复制构造函数

更新:建议重复的唯一解决这个问题的一部分.理解发生了什么的关键(首次创建临时引用的事实)在那里没有解释.

这是我第一次使用隐式转换,所以我写了这个:

class A {};

class B {
public:
    B(A& other) {}
    // Copy constructor
    B(const B& other) {}
};

int main() {
    A foo;
    B bar = foo;
}
Run Code Online (Sandbox Code Playgroud)

这按预期编译,但是如果我删除了const,我的编译器(gcc版本4.8.4)在赋值时产生,带有错误消息我无法理解:

test.cc: In function ‘int main()’:
test.cc:12:13: error: no matching function for call to ‘B::B(B)’
     B bar = foo;
             ^
test.cc:12:13: note: candidates are:
test.cc:7:5: note: B::B(B&)
     B(B& other) {}
     ^
test.cc:7:5: note:   no known conversion for argument 1 from ‘B’ to ‘B&’
test.cc:5:5: note: …
Run Code Online (Sandbox Code Playgroud)

c++

4
推荐指数
2
解决办法
360
查看次数

T :: T(T&)有什么用?

为什么会出现T::T(T&)时,有T::T(const T&)哪个更适合copy

(可能它用于实现move语义???)

原始描述(证明是错误的melpomene):

C++11,支持一种新形式的复制构造函数T::T(T&)(来自cppreferene/Copy构造函数隐式声明的复制构造函数),我想知道它的实际用途是什么?

c++ constructor

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

标签 统计

c++ ×4

constructor ×2

c++-faq ×1

const ×1

reference ×1

temporary ×1