簡體   English   中英

在 boost::noncopyable 類中,設置移動構造函數“=default”不編譯?

[英]In a boost::noncopyable class, setting the move constructor "=default" does not compile?

考慮以下代碼。 為了編譯它,我必須為移動構造函數提供一個主體。 具有“TestClass(TestClass&& other) = default”不會編譯並顯示錯誤“TestClass::TestClass(TestClass&&)' is implicitly deleted because the default definition would be ill-formed:”

為什么是這樣? 為什么它不能找出默認值?

#include <iostream>
#include <optional>
#include <boost/noncopyable.hpp>

class TestClass : public boost::noncopyable {
public:
    TestClass() {
        std::cout << "Constructed...\n";
    }

    TestClass(TestClass&& other) = default;

    //TestClass(TestClass&& other)  {
    //    std::cout << "Move constructor...\n";
    //}

    TestClass& operator=(TestClass&& other)  {
        std::cout << "Move assignment...\n";
        return *this;
    }
};

TestClass doThing() {
    std::optional<TestClass> tc = std::make_optional<TestClass>(TestClass{});
    return std::move(*tc);
}

int main() {
    const TestClass t = doThing();
}

https://godbolt.org/z/3f5zTT6a9

boost::noncopyable起源於C++11之前。 所以也許這個名字並沒有使這一點變得明顯,但它不僅使類不可復制,而且還使它不可移動(僅在 C++11 中添加了移動語義)。 如果不能移動基類,則移動構造函數的默認實現是不可能的。

它也應該由private繼承使用,而不是public

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM