为什么不允许对一个临时对象进行非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)
ref()可以修改临时对象. ref()允许您欺骗编译器并获取此临时对象的链接,这解决了我们的问题.此外:
他们说"为const引用分配一个临时对象可以延长这个对象的生命周期","但是对于非const引用却没有任何说法".我的其他问题.以下赋值是否延长了临时对象的生命周期?
X& x = getx().ref(); // OK
Run Code Online (Sandbox Code Playgroud) Vector(const Vector& other) // Copy constructor
{
x = other.x;
y = other.y;
Run Code Online (Sandbox Code Playgroud)
为什么参数是const?
更新:该建议重复的唯一解决这个问题的一部分.理解发生了什么的关键(首次创建临时引用的事实)在那里没有解释.
这是我第一次使用隐式转换,所以我写了这个:
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) 为什么会出现T::T(T&)时,有T::T(const T&)哪个更适合copy?
(可能它用于实现move语义???)
原始描述(证明是错误的melpomene):
在C++11,支持一种新形式的复制构造函数T::T(T&)(来自cppreferene/Copy构造函数隐式声明的复制构造函数),我想知道它的实际用途是什么?