有点令人惊讶(对我来说),以下两个程序编译成不同的输出,后者有更好的性能(用gcc和clang测试):
#include <vector>
int main()
{
std::vector<int> a(2<<20);
for(std::size_t i = 0; i != 1000; ++i) {
std::vector<int> b(2<<20);
a = b;
}
}
Run Code Online (Sandbox Code Playgroud)
与
#include <vector>
int main()
{
std::vector<int> a(2<<20);
for(std::size_t i = 0; i != 1000; ++i) {
std::vector<int> b(2<<20);
a = std::move(b);
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释为什么编译器会(或可以)不自动考虑b最后一个赋值中的xvalue并在没有显式强制转换的情况下应用移动语义std::move吗?
编辑:编译(g++|clang++) -std=c++11 -O3 -o test test.cpp
让
class A
{
std::vector<std::shared_ptr<int>> v_;
};
Run Code Online (Sandbox Code Playgroud)
现在我想添加v_使用两个公共成员函数的访问权限
std::vector<std::shared_ptr<int>> const & v() { return v_; }
Run Code Online (Sandbox Code Playgroud)
和
std::vector<std::shared_ptr<int const> const & v() const { TODO }
Run Code Online (Sandbox Code Playgroud)
我不能代替TODO使用return v_;,虽然.
一种选择是不返回引用而是复制.除了明显的性能损失之外,这也会使界面不那么令人满意.
另一种选择是TODO等于return reinterpret_cast<std::vector<std::shared_ptr<int const>> const &>(v_);
我的问题是,这是不确定的行为吗?或者,或者,是否有更好的选择,最好不使用reinterpret_cast?
c++ vector const-correctness undefined-behavior reinterpret-cast