相关疑难解决方法(0)

initializer_list和移动语义

我允许将元素移出std::initializer_list<T>

#include <initializer_list>
#include <utility>

template<typename T>
void foo(std::initializer_list<T> list)
{
    for (auto it = list.begin(); it != list.end(); ++it)
    {
        bar(std::move(*it));   // kosher?
    }
}
Run Code Online (Sandbox Code Playgroud)

由于std::intializer_list<T>需要特殊的编译器注意并且没有像C++标准库的普通容器那样的值语义,所以我宁愿安全而不是抱歉并且问.

c++ templates initializer-list move-semantics c++11

88
推荐指数
2
解决办法
1万
查看次数

为什么复制和移动构造函数一起调用?

请考虑以下代码:

#include <iostream>
#include <vector>
using namespace std;

class A
{
public:
     A(int) { cout << "int" << endl; }
     A(A&&) { cout << "move" << endl; }
     A(const A&) { cout << "copy" << endl; }
};

int main()
{
    vector<A> v
    {
        A(10), A(20), A(30)
    };

    _getch();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

int
int
int
copy
copy
copy
Run Code Online (Sandbox Code Playgroud)

A(10),A(20)并且A(30)是临时对象,对不对?

那么为什么复制构造函数被调用?不应该调用移动构造函数吗?

路过move(A(10)),move(A(20)),move(A(30))相反,输出为:

int
move
int
move
int
move
copy …
Run Code Online (Sandbox Code Playgroud)

c++ copy-constructor move-constructor move-semantics c++11

21
推荐指数
2
解决办法
1569
查看次数

C++如何为初始化为向量的类创建移动语义

我想在一个将在std :: vector中实例化的类上定义一个移动构造函数.但是,移动构造函数似乎会干扰向量的初始化.

#include <iostream>
#include <vector>
class cell
{
private:
int m_value;
public:
  void clear()  {m_value = 0;}
  cell(int i = 0): m_value(i) {}
  cell(const cell&& move): m_value(move.m_value) {} //move constructor
  cell& operator= (const cell& copy)
  {
    if (&copy == this) return *this;
    clear();
    m_value = copy.m_value;
    return *this;
  }
  int getValue() const {return m_value;}
};

int main()
{
cell mycell {3}; // initializes correctly
std::vector<cell> myVec {1, 2, 3, 4}; // compile error.
return 0;
}
Run Code Online (Sandbox Code Playgroud)

我已经做了很多研究,但还没有找到解决这个问题的方法.C++编程的新手.

编辑:我的类最终会有更多的m_value,包括一些非基本类型,因此我不想使用默认的复制构造函数.

c++ move vector

0
推荐指数
1
解决办法
95
查看次数