简体   繁体   English

C++ 对 class 使用 std::fill 并删除分配运算符

[英]C++ use std::fill for class with deleted assign operator

Suppose I have a range of objects假设我有一系列对象

class X {
public:
    X()
        : X(0) {
    }
    X(size_t num)
        : x_(num) {
    }
    X(const X& other) = delete;
    X& operator=(const X& other) = delete;
    X(X&& other) {
        x_ = exchange(other.x_, 0);
    }
    X& operator=(X&& other) {
        x_ = exchange(other.x_, 0);
        return *this;
    }
    size_t GetX() const {
        return x_;
    }

private:
    size_t x_;
};

With this in mind I can't use std::fill as operator= is deleted.考虑到这一点,我不能使用 std::fill 因为 operator= 被删除。 What is the right way to fill the range for this kind of object?填充这种 object 范围的正确方法是什么?

Source object of std::fill is const . std::fill的源 object 是const const object cannot be used as source of move operation. const object 不能用作移动操作的源。

You can add helper class with conversion operator to X , every time when *first = value;您可以将带有转换运算符的助手 class 添加到X ,每次*first = value; (look at possible implementation of std::fill ) is called, temporary of X is returned and move operation is performed: (查看std::fill 的可能实现)被调用,返回 X 的临时值并执行移动操作:

template<size_t N>
struct Helper {
    X MakeTemp() const { return X(N); }
    operator X () const { return MakeTemp(); }
};

int main(){
    std::vector<X> v;
    v.resize(10);
    std::fill(v.begin(), v.end(),Helper<10>{});

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C++ 使用带有基类的已删除函数 std::unique_ptr - C++ use of deleted function std::unique_ptr with Base class 如何在C ++中为运算符分配std :: function? - How do I assign an std::function to an operator in C++? 是否可以在 C++ 中使用 std::map 与 class 没有任何复制运算符? - Is is possible to use std::map in C++ with a class without any copy operator? C++ 编译器错误:使用已删除的 function std::variant() - C++ compiler error: use of deleted function std::variant() C ++ std :: thread“尝试使用已删除的函数” - C++ std::thread “Attempt to use a deleted function” 在 C++ 中覆盖 &lt;&lt; 运算符时如何正确遵守 std::setw 和 std::fill - How to properly honor std::setw and std::fill when overriding << operator in C++ 是否可以使用三元运算符“?”来填充C / C ++中的数组列表? - Is it possible to use the ternary operator “?” to fill an array list in C/C++? C ++-如何使用 <random> 填充std :: array - c++ - How to use <random> to fill std::array C ++中std :: set的自定义比较运算符和自定义类 - Custom comparison operator and custom class for std::set in C++ C ++类运算符重载不适用于std :: sort - C++ class operator overloads don't work with std::sort
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM