c++ 为什么bind_front要复制

cu6pst1q  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(132)

我以为bind_front会完美转发,但它似乎复制了。我在这里错过了什么:

class CustomObject {
public:
    // Constructor
    CustomObject(int value) : value(value) {
        std::cout << "Constructor: " << value << std::endl;
    }

    // Copy Constructor
    CustomObject(const CustomObject& other) : value(other.value) {
        //this is called
        std::cout << "Copy Constructor: " << value << std::endl;
    }

private:
    int value;
};

void func(const CustomObject& a, int b, int c) {
    std::cout << ", " << b << ", " << c << std::endl;
}

int main() {
    CustomObject A{ 5 };
    auto boundFunc = std::bind_front(func, A, 2, 2);
    boundFunc();
   
    return 0;

}

字符串
我认为它将perfec转发到func,而不是移动/复制

jgovgodb

jgovgodb1#

根据documentation
std::bind_frontstd::bind_back的参数会被复制或移动,并且永远不会通过引用传递,除非 Package 在std::refstd::cref中。
在你的例子中,这是完美的:

auto boundFunc = std::bind_front(func, std::cref(A), 2, 2);

字符串

相关问题