如何防止在for_each结束时调用复制构造函数?

gra*_*eds 2 c++ c++11 visual-studio-2013

在下面的代码中我希望看到,COD但实际输出是CODD.我最终确定存在对复制构造函数的隐藏调用,因此现在输出COUDD.

虽然我已经发现为什么额外的析构函数调用我不明白为什么它被生成并且阻止我修复它.我认为它必须来自for_each返回一元函数,但由于我没有通过值传递或返回(或者我认为不是),因此不应该调用复制构造函数.一切都应该参考.我可以使用指针,但由于test_enc对象应该是调用期间的范围,因此for_each引用更好.

struct test_enc
{
    test_enc(std::string& ref) : ref_(ref) {
        ref_.push_back('C');
    }
    test_enc(const test_enc& other) : ref_(other.ref_) {
        ref_.push_back('U');
    }
    ~test_enc() {
        ref_.push_back('D');
    }
    void operator()(const char byte) {
        ref_.push_back('O');
    }
    test_enc& operator=(const test_enc&) = delete;
    std::string& ref_;
};

TEST(CheckTestEncoderEncodesExactlyOneByte)
{
    const std::string unencoded_string("M");
    std::string encoded_string;
    std::for_each(unencoded_string.begin(), unencoded_string.end(), test_enc(encoded_string));
    CHECK_EQUAL(3U, encoded_string.size());
    CHECK_EQUAL("COD", encoded_string); // get "COUDD"
}
Run Code Online (Sandbox Code Playgroud)

如何在没有不需要的复制构造函数的情况下调用test_enc?

jua*_*nza 5

std::for_each以价值来看待它的一元仿函数.所以你无法避免复制,但你可以通过使用std::reference_wrapper:模仿参考语义:

#include <functional>

std::string encoded_string;
test_encoded test_str(encoded_string);
std::for_each(unencoded_string.begin(), 
              unencoded_string.end(), 
              std::ref(test_str));
Run Code Online (Sandbox Code Playgroud)