c++ - 为什么不从临时对象(operator+ 的结果)中移动不调用构造函数?

标签 c++ c++11 move-constructor

既然已经回答了:请不要费心阅读这个问题,它有点冗长,可能不值得您花时间。我的代码中存在错误,这就是未调用移动构造函数的原因。检查答案以获取详细信息。请记住,RVO 和 NRVO(命名返回值优化)可能会导致调用未按您预期发生。


我希望为这一行调用移动构造函数,但调用了复制构造函数:

Ding d3 = d1 + d2;

Ding 类有一个用户定义的移动构造函数和 on operator+ 重载。我希望移动构造函数被调用的原因是 operator+ 返回一个临时对象,一个右值引用,因此可以进行移动优化。

我在这里写的所有内容都可能是错误的,因为我是 C++ 初学者。这是代码:

// Copied and modified code from here: https://stackoverflow.com/a/3109981
#include <iostream>
#include <cstring>

struct Ding {
    char* data;

    Ding(const char* p) {
        std::cout << " ctor for: " << p << "\n";
        size_t size = strlen(p) + 1;
        data = new char[size];
        memcpy(data, p, size);
    }

    ~Ding() {
        std::cout << " dtor for: " << data << "\n";
        delete[] data;
    }

    Ding(const Ding& that) {
        std::cout << " copy for: " << that.data << "\n";
        size_t size = strlen(that.data) + 1;
        data = new char[size];
        memcpy(data, that.data, size);
    }

    Ding(Ding&& that) {
        std::cout << " MOVE for: " << that.data << "\n";
        data = that.data;
        that.data = nullptr;
    }

    Ding& operator=(Ding that) {
        std::cout << " assignment: " << that.data << "\n";
        std::swap(data, that.data);
        return *this;
    }

    Ding& operator+(const Ding that) const {
        std::cout << " plus for: " << that.data << "\n";
        size_t len_this = strlen(this->data);
        size_t len_that = strlen(that.data);
        char * tmp = new char[len_this + len_that + 1];
        memcpy( tmp,          this->data, len_this);
        memcpy(&tmp[len_this], that.data, len_that + 1);
        Ding * neu = new Ding(tmp);
        return *neu;
    }
};

void print(Ding d) {
    std::cout << "  (print): " << d.data << std::endl;
}

int main(void) {
    std::cout << "putting a Ding on the stack\n";
    Ding d1("jajaja");
    std::cout << "calling print routine\n";
    print(d1);
    std::cout << "putting a second Ding on the stack\n";
    Ding d2("nein");
//  std::cout << "calling print routine\n";
//  print(d2);
    std::cout << "Putting a third Ding on the stack, init from + op ...\n";
    std::cout << "... so expecting so see MOVE ctor used ...\n";
    Ding d3 = d1 + d2;
//  std::cout << "calling print routine\n";
//  print(d3);
    std::cout << "End of main, dtors being called ...\n";
}

VC2010 Express 和 MinGW (GCC 4.6) 的编译器调用(在 Win7 上)如下:

cl /nologo /W4 /EHsc /MD move-sem.cpp
g++ -std=c++0x move-sem.cpp -o move-gcc.exe

两个二进制文件产生相同的输出(程序结束时没有销毁顺序):

putting a Ding on the stack
 ctor for: jajaja
calling print routine
 copy for: jajaja
  (print): jajaja
 dtor for: jajaja
putting a second Ding on the stack
 ctor for: nein
Putting a third Ding on the stack, init from + op ...
... so expecting so see MOVE ctor used ...
 copy for: nein
 plus for: nein
 ctor for: jajajanein
 dtor for: nein
 copy for: jajajanein
End of main, dtors being called ...
 dtor for: jajajanein
 dtor for: nein
 dtor for: jajaja

回想一下这个长文本之后的问题是什么:为什么不为 Ding d3 = d1 + d2; 调用移动构造函数?

我知道还有其他问题关于为什么移动运算符(operator)没有被调用,但我无法将他们的答案映射到这种情况。

更新

我根据 David Rodriguez 的评论对程序进行了如下更改:

--- move-sem.cpp.orig   2012-03-17 17:00:56.901570900 +0100
+++ move-sem.cpp        2012-03-17 17:01:14.016549800 +0100
@@ -36,15 +36,14 @@
                return *this;
        }

-       Ding& operator+(const Ding that) const {
+       Ding operator+(const Ding that) const {
                std::cout << " plus for: " << that.data << "\n";
                size_t len_this = strlen(this->data);
                size_t len_that = strlen(that.data);
                char * tmp = new char[len_this + len_that + 1];
                memcpy( tmp,          this->data, len_this);
                memcpy(&tmp[len_this], that.data, len_that + 1);
-               Ding * neu = new Ding(tmp);
-               return *neu;
+               return tmp;
        }
 };

然后我使用上面提到的编译器调用重新编译程序并得到一个输出,其中一个拷贝 (copy for: jajajanein) 被删除。然后我尝试了以下行:

g++ -std=c++0x -fno-elide-constructors move-sem.cpp -o move-gcc.exe

还有塔塔!现在我看到 move ctor 在工作了! ...但我认为现在还有另一个错误,新的 move-gcc.exe 的输出不再列出 dtor 调用:

putting a Ding on the stack
 ctor for: jajaja
calling print routine
 copy for: jajaja
  (print): jajaja
 dtor for: jajaja
putting a second Ding on the stack
 ctor for: nein
Putting a third Ding on the stack, init from + op ...
... so expecting so see MOVE ctor used ...
 copy for: nein
 plus for: nein
 ctor for: jajajanein
 MOVE for: jajajanein
 dtor for:

第二次更新

我用以下(可能同样糟糕的)代码替换了错误的 operator+:

Ding& operator+=(const Ding & rhs) {
    std::cout << " op+= for: " << data << " and " << rhs.data << "\n";
    size_t len_this = strlen(this->data);
    size_t len_that = strlen(rhs.data);
    char * buf = new char[len_this + len_that + 1];
    memcpy( buf,         this->data, len_this);
    memcpy(&buf[len_this], rhs.data, len_that + 1);
    delete[] data;
    data = buf;
    return *this;
}

Ding operator+(const Ding & rhs) const {
    Ding temp(*this);
    temp += rhs;
    return temp;
}

我还从析构函数中删除了以下行,它阻止了程序异常终止:

std::cout << " dtor for: " << data << "\n";

移动构造函数现在在使用 MSVC 和 g++ -std=c++0x -fno-elide-constructors 编译时被调用。

最佳答案

    Ding * neu = new Ding(tmp);
    return *neu;

这是错误的。您正在动态分配一个 Ding,然后强制复制它。因为 Ding 是动态分配的,您正在泄漏它,它的生命周期超出了 return 语句,编译器无法移动。请注意,您不是返回一个临时的。

将其更改为:

    return Ding(tmp);

甚至:

    return tmp;

由于您的构造函数采用const char* 不是显式,因此编译器将使用它来创建一个新的Ding 对象。在这两种情况下,临时对象的生命周期都不会超出 return 语句,编译器将移动

(此答案假定您了解从返回的对象到 d3 的拷贝已被省略,如果那是您期望移动的位置,那么编译器会做一些更好的事情:避免操作完全)。

编辑 由于 DeadMG 已经编写了 规范形式但它包含错误我将跟进:

关于运算符重载有很多要说的,但一个常见的建议(我给出并遵循的建议)是将 operatorX= 实现为成员函数(它是应用于左手的操作side) 然后将 operator+ 实现为前者的自由函数。在 C++11 中将是:

class X {
   X& operator+=( X const & ); // we do not modify the rhs internally
};
X operator+( X lhs, X const & rhs ) {
  lhs += rhs;                  // reuse implementation
  return lhs;
}

一些注意事项:operator+ 是一个自由函数,因此在类型方面是对称的。所有可能在右侧发生的隐式转换在 lhs 中也可用。在您的特定情况下, Ding 可从 const char* 隐式转换,这意味着通过使用自由函数 operator+ 您可以编写:

Ding d( "A" );
const char* str = "B";
d + d;     // no conversions
d + str;   // conversion on the right hand side
str + d;   // conversion on the left hand side

通过将 operator+= 定义为公共(public)成员函数,您需要编写一个单独的实现并且该实现可以重用,因此您可以获得两个运算符的成本为一个(以及额外的三行代码这是微不足道的)。

按值论证并按值返回。如果参数是临时的,这使编译器能够省略对参数的拷贝。因为有一个移动构造函数,所以也不会有任何内部拷贝,参数将被修改移动到返回对象。 (第二个拷贝不能省略)。

我在运算符重载方面写的比这多一点 here前段时间...它没有明确处理优化(移动),但那里还有其他帖子处理它的 C++03 版本。从那到 C++11 特性,您应该能够填补空白。

关于c++ - 为什么不从临时对象(operator+ 的结果)中移动不调用构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9751305/

相关文章:

c++ - 移动构造函数和移动赋值

c++ - 无法将 big.Int 从 Go 序列化为 C++

c++ - 为什么 shared_ptr<> 必须分别为控制 block 和管理对象分配?

c++ - 编译 cpp 文件时出错 (ros)

c++ - 为什么指向 int 的指针转换为 void* 而指向函数的指针转换为 bool?

c++11 - 头文件中定义的函数的重复符号

c++ - 移动构造函数会自动初始化未列出的成员吗?

c++ - 我看到的所有基于 std::move() 的 std::swap() 实现都是错误的吗?

C++ 名称与 typedef 别名和继承名称的冲突

c++ - opencv c++比较不同图像中的关键点位置