为什么不从临时对象中调用move ctor进行构造(运算符+的结果)



既然已经回答了:不要麻烦阅读这个问题,它有点长,可能不值得你花时间。我的代码中有错误,这就是为什么没有调用move构造函数的原因。查看答案以了解详细信息。请记住,RVO和NRVO(命名返回值优化)可能会导致调用没有按预期发生。


我希望为这一行调用move ctor,但却调用了copy ctor:

Ding d3 = d1 + d2;

Ding类有一个用户定义的move ctor和on运算符+重载。我希望调用move ctor的原因是运算符+返回一个临时对象,一个右值引用,因此可以进行move优化。

我在这里写的所有东西都可能是错误的,因为我是一个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 stackn";
    Ding d1("jajaja");
    std::cout << "calling print routinen";
    print(d1);
    std::cout << "putting a second Ding on the stackn";
    Ding d2("nein");
//  std::cout << "calling print routinen";
//  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 routinen";
//  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;调用move构造函数?

我知道还有其他问题,为什么搬家工人没有接到电话,但我无法将他们的答案映射到这个案例中。

  • 为什么这个C++0x代码不调用move构造函数
  • 为什么这段代码试图调用复制构造函数
  • 在C++0x中未调用Move构造函数

更新

根据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

还有塔塔!现在我看到移动的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进行编译时,将调用move构造函数。

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

这是错误的。您正在动态分配Ding,然后强制它的副本。由于Ding是动态分配的,您正在泄漏它,它的生存期超出了return语句,编译器无法从中移动。请注意,您是而不是返回临时的。

将其更改为:

    return Ding(tmp);

甚至:

    return tmp;

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

(这个答案假设您知道从返回对象到d3的副本已经被消除,如果这是您期望的移动位置,那么编译器会做得更好:完全避免操作)。

编辑由于DeadMG编写了一个规范形式,但其中包含错误,我将跟进:

关于运算符重载有很多话要说,但一个常见的建议(我给出并遵循的建议)是将operatorX=实现为成员函数(它是应用于左手边的操作),然后根据前者将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+=定义为公共成员函数,您需要编写一个实现,并且该实现可以重用,因此您只需花费一个运算符就可以获得两个运算符(以及三行额外的琐碎代码)。

按值参数和按值返回。这使编译器能够在参数是临时参数的情况下消除参数的副本。由于存在移动构造函数,因此也不会有任何内部副本,参数将被修改移到返回对象。(第二个副本不能被删除)。

不久前,我在这里写了更多关于运算符重载的文章。。。它没有明确处理优化(移动),但还有其他帖子处理它的C++03版本。从那到C++11功能,你应该能够填补空白。

没有可移动的内容。

不能从d1d2移动,因为那样会破坏它们。并且不能移动operator+的返回值,因为这是一个引用。

您没有编写正确的加法运算符。规范形式是

Ding operator+(Ding other) const {
    other += this;
    return other; 
    // return std::move(other) if you're on MSVC 
    // which sometimes doesn't do this properly
}
Ding& operator+=(const Ding& other);

您的代码会出现许多问题,比如内存泄漏,这也是由错误的运算符重载引起的。

此外,不要忘记RVO和NRVO对预期产出的潜在影响。

最新更新