在 msvc 中引用临时文件

2023-06-03C/C++开发问题
1

本文介绍了在 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 中引用临时文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6