为什么从未调用我的复制赋值运算符?

时间:2015-02-12 15:39:53

标签: c++ c++14 assignment-operator

我正在使用c ++ 14,我想知道为什么我的赋值运算符从未被调用过。实现似乎是正确的,我禁用了优化(-fno-elide-constructors -O0)这是我缺少的某种编译器优化还是我的代码有问题?

源代码

#include <iostream>

using namespace std;

int num = 0;

#define LOG_LINE(a) cout << "\n" << (++num) << ".)------------------------> " << #a << "\n"
#define LOG_TEXT cout << "called " << __PRETTY_FUNCTION__ << "\n"

struct Klass {
    Klass() { LOG_TEXT; }
    ~Klass() { LOG_TEXT; }

    // copy
    Klass(const Klass&) { LOG_TEXT; }
    Klass& operator=(const Klass&) { LOG_TEXT; return *this; }

    // move
    Klass(Klass&&) { LOG_TEXT; }
    Klass& operator=(Klass&&) { LOG_TEXT; return *this; }
};


int main() {

    LOG_LINE(expecting normal contruction - OK);
    auto k1 = Klass{};
    auto k12 = Klass();

    LOG_LINE(expecting assignment operator - FAIL);
    auto k2 = k1;

    LOG_LINE(expecting copy construction - OK);
    auto k3 = Klass(k2);

    LOG_LINE(expecting move assignment - FAIL);
    auto k4 = std::move(k3);

    LOG_LINE(expecting move construction - OK);
    auto k5 = Klass(std::move(k4));

    LOG_LINE(expecting destruction of remaining objects - OK);
    (void) k5;

    return 0;
}

输出

1.)------------------------> expecting normal contruction - OK
called Klass::Klass()
called Klass::Klass(Klass &&)
called Klass::~Klass()
called Klass::Klass()
called Klass::Klass(Klass &&)
called Klass::~Klass()

2.)------------------------> expecting assignment operator - FAIL
called Klass::Klass(const Klass &)

3.)------------------------> expecting copy construction - OK
called Klass::Klass(const Klass &)
called Klass::Klass(Klass &&)
called Klass::~Klass()

4.)------------------------> expecting move assignment - FAIL
called Klass::Klass(Klass &&)

5.)------------------------> expecting move construction - OK
called Klass::Klass(Klass &&)
called Klass::Klass(Klass &&)
called Klass::~Klass()

6.)------------------------> expecting destruction of remaining objects - OK
called Klass::~Klass()
called Klass::~Klass()
called Klass::~Klass()
called Klass::~Klass()
called Klass::~Klass()
called Klass::~Klass()

其他信息

我正在使用:

clang ++ --version
Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin14.0.0
Thread model: posix

编译:     clang++ source.cpp -std=c++1y -o s -Wpedantic -Wall -Wextra -fno-elide-constructors -O0 && ./s

1 个答案:

答案 0 :(得分:8)

auto k2 = k1;

是复制初始化,而不是赋值;它会调用复制构造函数。如果您将该行更改为以下内容,则会执行您期望的操作

Klass k2;   // default construction
k2 = k1;    // copy assignment

类似地

Klass k4;            // default construction
k4 = std::move(k3);  // move assignment