简体   繁体   English

C ++ 11移动语义和右值引用

[英]C++11 move semantics and rvalue reference

Consider the following code: 考虑以下代码:

class StringTokenizer 
{
private:
    char m_delimiter;
    std::istringstream m_string;

public:
    explicit StringTokenizer(const std::string& str, char delimiter)
    : m_string(str)
    , m_delimiter(delimiter)
    {
    }

    template <class Container>
    operator Container ()
    {
        Container container;
        for (std::string token; std::getline(m_string, token, m_delimiter); )
        {
            container.insert(container.end(), token);
        }
        return container;
    }
};

This is the usage: 这是用法:

vector<string> tmp = StringTokenizer("123 456", ' '); //Please note the implicit conversion

When debugging the following happens (Using VS2013): 调试时会发生以下情况(使用VS2013):

At the return statement of conversion operator 在转换运算符的return语句中

  1. new vector constructed from container by moving 通过移动从container构造新的向量
  2. container gets destructed container被破坏

After function return: 函数返回后:

  1. tmp is constructed by copy constructor tmp由复制构造函数构造

My question is why isn't tmp constructed by move constructor ? 我的问题是为什么tmp不是由move构造函数构造的?

As I understand things function return type is rvalue and should be moved. 据我了解,函数返回类型是右值,应该被移动。

VS2013 doesn't automatically generate the move constructor/assignment. VS2013不会自动生成move构造函数/赋值。 This is solved in later versions. 这在以后的版本中已解决。

https://msdn.microsoft.com/en-us/library/hh567368.aspx#rvref https://msdn.microsoft.com/zh-CN/library/hh567368.aspx#rvref

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM