nothrow_move_constructible
全部标签 假设我有以下代码:intmain(){std::vectorstrs;std::stringvar("HelloWorld");//Makesomemodificationsto'var'strs.push_back(std::move(var));}我要指出的示例部分是std::move()的用法。基本上我担心push_back()调用的拷贝。假设我要添加的字符串非常大。我仍在学习C++11右值引用,所以我不确定编译器如何在没有std::move()的情况下优化拷贝(如果有的话)。谁能解释这是否是一种过早的优化(通常在所有要避免复制的情况下强制移动)?如果是这样,我应该期望编译器遵循
unique_ptr是否保证在move后存储nullptr?std::unique_ptrp1{newint{23}};std::unique_ptrp2{std::move(p1)};assert(!p1);//isthisalwaystrue? 最佳答案 可以,你可以在move之后和nullptr比较,保证比较相等。来自§20.8.1/4[unique.ptr]Additionally,ucan,uponrequest,transferownershiptoanotheruniquepointeru2.Uponcompletio
我目前正在学习C++,并尽量避免养成坏习惯。据我了解,clang-tidy包含许多“最佳实践”,我尽量坚持使用它们(尽管我还不一定了解为什么它们被认为是好的),但是我不确定我是否理解这里的建议。我使用了教程中的这个类:classCreature{private:std::stringm_name;public:Creature(conststd::string&name):m_name{name}{}};这导致clang-tidy建议我应该按值而不是引用传递并使用std::move。如果我这样做了,我会收到将name设为引用的建议(以确保它不会每次都被复制)以及std::move不会出
重复使用move的容器的正确方法是什么?std::vectorcontainer;container.push_back(1);autocontainer2=std::move(container);//ver1:Donothing//container2.clear();//ver2:"Reset"container=std::vector()//ver3:Reinitializecontainer.push_back(2);assert(container.size()==1&&container.front()==2);根据我在C++0x标准草案中读到的内容;ver3似乎是正确的
我有一个std::vector某个类A的对象。该类是非平凡的,并且定义了复制构造函数和move构造函数。std::vectormyvec;如果我用A对象填充vector(使用例如myvec.push_back(a)),则使用复制构造函数A(constA&)实例化vector中元素的新拷贝。我能否以某种方式强制使用A类的move构造函数来代替? 最佳答案 您需要使用noexcept通知C++(特别是std::vector)您的move构造函数和析构函数不会抛出。然后当vector增长时会调用move构造函数。这是如何声明和实现受std
我可以将元素移出std::initializer_list吗?#include#includetemplatevoidfoo(std::initializer_listlist){for(autoit=list.begin();it!=list.end();++it){bar(std::move(*it));//kosher?}}由于std::intializer_list需要特别注意编译器,并且不像C++标准库的普通容器那样具有值语义,因此我宁愿安全而不愿后悔。 最佳答案 不,这不会按预期工作;您仍然会得到副本。我对此感到非常惊讶
这个问题在这里已经有了答案:c++11Returnvalueoptimizationormove?[duplicate](4个回答)关闭5年前。在这种情况下structFoo{};Foomeh(){returnstd::move(Foo());}我很确定move是不必要的,因为新创建的Foo将是一个xvalue。但是在这种情况下呢?structFoo{};Foomeh(){Foofoo;//dosomething,butknowingthatfoocansafelybedisposedof//butdoesthecompilernecessarilyknowit?//wemayhave
std::piecewise_construct,在中定义,具有内部链接,因为它被声明为constexpr。我想知道在header中使用std::piecewise_construct是否会违反ODR。例如:a.hpp#include#includestructpoint{point(intx,inty):x(x),y(y){}intx,y;};inlinestd::pairf(intx1,inty1,intx2,inty2){return{std::piecewise_construct,std::forward_as_tuple(x1,y1),std::forward_as_tup
std::piecewise_construct,在中定义,具有内部链接,因为它被声明为constexpr。我想知道在header中使用std::piecewise_construct是否会违反ODR。例如:a.hpp#include#includestructpoint{point(intx,inty):x(x),y(y){}intx,y;};inlinestd::pairf(intx1,inty1,intx2,inty2){return{std::piecewise_construct,std::forward_as_tuple(x1,y1),std::forward_as_tup
我的模板结构的移动构造函数中有一个static_assert。编译器是否需要考虑这个static_assert,即使复制省略是可能的?这是精简的场景:#includetemplatestructX{X(X&&){static_assert(std::is_same::value,"IntentionalFailure");}};autoimpl()->X;autotest()->decltype(impl()){returnimpl();}intmain(){test();}GCC和Clang同意评估static_assert并且编译失败。另一方面,MSCV和ICC可以很好地编译代码。