Reference a temporary in msvc(在 msvc 中引用临时文件)
问题描述
为什么这会在 MS Visual C++ 上编译?
Why does this compile on MS Visual C++?
struct myClass{};
void func(myClass& arg){}
void main() {
func( myClass() ); // works even though func only takes myClass&
} // (not const myClass&!!)
这是否也适用于其他编译器,或者是特定于 MSVC 的(甚至是编译器错误?).我什至可以像这样获得这个右值的引用:
Does this work on other compilers as well or is this MSVC specific (or even a compiler bug?). I can even get the reference on this rvalue like this:
void func(myClass* arg){}
int main() {
func( &myClass() );
}
这仅适用于使用构造函数临时创建的对象.这不适用于任何其他右值,例如 (myClass() + myClass()) ..
This works ONLY on Objects that are temporarily created with a constructor. This wouldn't work with any other rvalue like (myClass() + myClass()) for example..
推荐答案
它可以编译是因为 MSVC 有一个非标准兼容的扩展",允许将非常量引用绑定到临时文件.
It compiles because MSVC has a non-standard compliant "extension" that allows binding non-const references to temporaries.
第一个示例不应在符合标准的编译器上编译.
The first example should not compile on a standards compliant compiler.
在第二个示例中,您将使用临时地址来设置指针的值.这也应该导致错误.
In the second example, you are taking the address of a temporary to set the value of a pointer. This should also result in an error.
Clang 3.2 产生:
Clang 3.2 produces:
错误:获取类型为 'Foo' [-Waddress-of-temporary] 的临时对象的地址
error: taking the address of a temporary object of type 'Foo' [-Waddress-of-temporary]
而 GCC 4.7.3 产生
while GCC 4.7.3 produces
错误:取临时地址[-fpermissive]
error: taking address of temporary [-fpermissive]
这篇关于在 msvc 中引用临时文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 msvc 中引用临时文件


- STL 中有 dereference_iterator 吗? 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 静态初始化顺序失败 2022-01-01
- C++ 协变模板 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 近似搜索的工作原理 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01