我试图理解rvalue引用并移动C++ 11的语义.
这些示例之间有什么区别,哪些不会执行矢量复制?
std::vector<int> return_vector(void)
{
std::vector<int> tmp {1,2,3,4,5};
return tmp;
}
std::vector<int> &&rval_ref = return_vector();
Run Code Online (Sandbox Code Playgroud)
std::vector<int>&& return_vector(void)
{
std::vector<int> tmp {1,2,3,4,5};
return std::move(tmp);
}
std::vector<int> &&rval_ref = return_vector();
Run Code Online (Sandbox Code Playgroud)
std::vector<int> return_vector(void)
{
std::vector<int> tmp {1,2,3,4,5};
return std::move(tmp);
}
std::vector<int> &&rval_ref = return_vector();
Run Code Online (Sandbox Code Playgroud) 我正在回答一个问题并建议为大型类型返回按值,因为我相信编译器会执行返回值优化(RVO).但后来有人向我指出Visual Studio 2013没有在我的代码上执行RVO.
我在这里发现了一个关于Visual Studio无法执行RVO的问题,但在这种情况下,结论似乎是,如果真的很重要Visual Studio将执行RVO.在我的情况下它确实很重要,它对性能产生了重大影响,我已经通过分析结果证实了这一点.这是简化的代码:
#include <vector>
#include <numeric>
#include <iostream>
struct Foo {
std::vector<double> v;
Foo(std::vector<double> _v) : v(std::move(_v)) {}
};
Foo getBigFoo() {
std::vector<double> v(1000000);
std::iota(v.begin(), v.end(), 0); // Fill vector with non-trivial data
return Foo(std::move(v)); // Expecting RVO to happen here.
}
int main() {
std::cout << "Press any key to start test...";
std::cin.ignore();
for (int i = 0; i != 100; ++i) { …Run Code Online (Sandbox Code Playgroud) 我在我的代码中声明了以下内容
vector <const A> mylist;
Run Code Online (Sandbox Code Playgroud)
我得到以下编译错误 -
new_allocator.h:75: error: `const _Tp* __gnu_cxx::new_allocator<_Tp>::address(const _Tp&) const \[with _Tp = const A]' and `_Tp* __gnu_cxx::new_allocator<_Tp>::address(_Tp&) const [with _Tp = const A]' cannot be overloaded
Run Code Online (Sandbox Code Playgroud)
但如果宣布 -
vector <A> mylist;
Run Code Online (Sandbox Code Playgroud)
我的代码编译.
在这种情况下不允许使用const吗?
我在这里复制我的代码供大家参考 -
#include <iostream>
#include <vector>
using namespace std;
class A
{
public:
A () {cout << "default constructor\n";}
A (int i): m(i) {cout << "non-default constructor\n";}
private:
int m;
};
int main (void)
{
vector<const A> mylist;
mylist.push_back(1);
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我有一个向量作为类的成员,我想通过getVector()函数返回它的引用,以便以后能够修改它.是不是更好地练习函数getVector()为const?但是我在下面的代码中收到错误"在类型的绑定引用中删除了限定符...".应该修改什么?
class VectorHolder
{
public:
VectorHolder(const std::vector<int>&);
std::vector<int>& getVector() const;
private:
std::vector<int> myVector;
};
std::vector<int> &VectorHolder::getVector() const
{
return myVector;
}
Run Code Online (Sandbox Code Playgroud)