gpt4 book ai didi

c++ - 在 C++ 11 中将非常量左值引用绑定(bind)到右值是否有效?(已修改)

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:35:00 25 4
gpt4 key购买 nike

我知道在 c++03 中,非常量引用不能绑定(bind)到右值。

T& t = getT(); 无效,在 c++11 中,我们可以这样做:T&& t = getT(); 但是上面的代码,应该在 c++11 中工作吗?

我用 vs11 测试了下面的代码:

 Foo getFoo() {
return Foo();
}

void fz(Foo& f) {
}

int getInt() {
return int();
}

void iz(int& i) {
}

int main() {
{
Foo& z = getFoo(); //ok
fz(getFoo()); //ok

int& z2 = getInt(); //error: initial value of reference to non-const must be an lvalue
iz(getInt()); //same as above
}
}

Foo 是一个自定义类,我不明白为什么前两行编译。 z 引用的临时对象在内部范围的末尾析构主要的。标准对此有任何说明吗?

class Foo {
public:
Foo() {
std::cout << "constructed\n";
}
~Foo() {
std::cout << "destructed\n";
}
};

我刚看到一个类似的问题:One VS2010 bug ? Allowing binding non-const reference to rvalue WITHOUT EVEN a warning?

最佳答案

should that work in c++11?

不,不应该。

Foo is a custom class, I don't understand why the first two line compiles

它只能用 MSVC 编译。 MSVC 有一个(可以说是有用的)编译器扩展,它允许将用户定义类型的左值绑定(bind)到右值,但标准本身禁止这样做。参见,例如,this live example GCC 4.7.2 拒绝编译您的代码。

Does the standard say anything about this?

确实如此。根据 C++11 标准的第 8.5.3/5 段:

A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows:

— If the reference is an lvalue reference and the initializer expression

— is an lvalue (but is not a bit-field), and “cv1 T1” is reference-compatible with “cv2 T2,” or

— has a class type (i.e., T2 is a class type), where T1 is not reference-related to T2, and can be implicitly converted to an lvalue of type “cv3 T3,” where “cv1 T1” is reference-compatible with “cv3
T3
” [...],

然后引用绑定(bind)到第一种情况下的初始化表达式左值和左值结果 第二种情况下的转换(或者,在任何一种情况下,到适当的基类子对象 物体)。 [...]

[ ...]

否则,引用应为对非 volatile 常量类型的左值引用(即,cv1 应为 const),或者引用应该是一个右值引用。 [示例:

double& rd2 = 2.0; // error: not an lvalue and reference not const
int i = 2;
double& rd3 = i; // error: type mismatch and reference not const

——结束示例 ]

关于c++ - 在 C++ 11 中将非常量左值引用绑定(bind)到右值是否有效?(已修改),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16493524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com