我正在维基百科上C++11
阅读关于类型推断功能的这篇文章.
有一个例子,我引述:
#include <vector>
int main() {
const std::vector<int> v(1);
auto a = v[0]; // a has type int
decltype(v[1]) b = 1; // b has type const int&, the return type of
// std::vector<int>::operator[](size_type) const
auto c = 0; // c has type int
auto d = c; // d has type int
decltype(c) e; // e has type int, the type of the entity named by c
decltype((c)) f = …
Run Code Online (Sandbox Code Playgroud) §3.10第9节说"非类别rvalues总是有cv不合格类型".这让我很奇怪......
int foo()
{
return 5;
}
const int bar()
{
return 5;
}
void pass_int(int&& i)
{
std::cout << "rvalue\n";
}
void pass_int(const int&& i)
{
std::cout << "const rvalue\n";
}
int main()
{
pass_int(foo()); // prints "rvalue"
pass_int(bar()); // prints "const rvalue"
}
Run Code Online (Sandbox Code Playgroud)
根据标准,对于非类型类型没有const rvalue,但bar()
更喜欢绑定const int&&
.这是编译器错误吗?
编辑:显然,this
也是一个const rvalue :)
编辑:这个问题似乎在g ++ 4.5.0中得到修复,现在两行打印"rvalue".
我想检查一下我对此事的理解和结论.
在IRC上,有人问:
绑定到临时对象
const_cast
的const
引用是否可以接受?
翻译:他有一个临时的ref-to-const,他想抛弃它const
来修改它.
我的回答是我之前曾问过一个类似的问题,其中的共识似乎是临时性本身并不是天生的const
,因此你可以抛弃const
你对它们的引用的性质,并通过结果修改它们.而且,只要原始参考const
仍然存在,这不会影响临时的生命周期.
那是:
int main()
{
const int& x = int(3);
int& y = const_cast<int&>(x);
y = 4;
cout << x;
}
// Output: 4
// ^ Legal and safe
Run Code Online (Sandbox Code Playgroud)
我对吗?
(当然,这些代码是否真的是可取的完全是另一回事!)
在3.10/10,标准说:
为了修改对象,对象的左值是必要的,除了在某些情况下也可以使用类类型的右值来修改它的指示对象.[示例:调用对象(9.3)的成员函数可以修改对象.]
因此,除非在某些情况下,否则rvalues是不可修改的.我们被告知调用成员函数是其中一个例外.这给出了除了调用成员函数之外还有修改对象的方法的想法.我想不出办法.
如何在不调用成员函数的情况下修改对象?
代码如下:
#include <iostream>
using namespace std;
class A {
};
A rtByValue() {
return A();
}
void passByRef(A &aRef) {
// do nothing
}
int main() {
A aa;
rtByValue() = aa; // compile without errors
passByRef(rtByValue()); // compile with error
return 0;
}
Run Code Online (Sandbox Code Playgroud)
g ++编译器给出以下错误:
d.cpp: In function ‘int main()’:
d.cpp:19:23: error: invalid initialization of non-const reference of type ‘A&’ from an rvalue of type ‘A’
d.cpp:12:6: error: in passing argument 1 of ‘void passByRef(A&)’
Run Code Online (Sandbox Code Playgroud)
它说我不能将rvalue作为非const引用的参数传递,但是我很困惑的是为什么我可以分配给这个rvalue,就像代码所示.
我怀疑我们是否可以做以下事情.
假设我已经创建类的两个实例A
,即obj1
和obj2
和类A
有成员函数show()
.
我可以使用以下内容吗?
(obj1+obj2).show()
Run Code Online (Sandbox Code Playgroud)
如果有,怎么样?如果不是,为什么不可能呢?
假设我有以下内容:
class foo
{
public:
foo& Ref() { return *this; }
int stuff;
};
void do_stuff(foo& f)
{
f.stuff = 1;
}
int main()
{
do_stuff(foo().Ref());
}
Run Code Online (Sandbox Code Playgroud)
我正在通过左值参考修改右值.这合法吗?如果是,如果没有,有人可以解释原因并提供标准中的相关部分吗?