gpt4 book ai didi

c++ - move 左值引用参数是不好的做法吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:17:56 24 4
gpt4 key购买 nike

我最初认为 move 左值引用参数是不好的做法。 C++ 开发人员社区确实普遍认同这一点吗?

当我调用一个具有 R 值引用参数的函数时,很明显我必须期望可以 move 传递的对象。对于具有 L 值引用参数的函数,这并不是那么明显(在 C++11 引入 move 语义之前,这根本不可能)。

但是,我最近采访过的其他一些开发人员不同意应避免 move 左值引用。是否有强有力的论据反对它?还是我的意见有误?

由于我被要求提供一个代码示例,这里有一个(见下文)。这是一个仅用于演示问题的人为示例。很明显,在调用modifyCounter2()之后,再调用getValue()会导致segmentation fault。但是,如果我是 getValue() 的用户而不知道其内部实现,我会感到非常惊讶。另一方面,如果参数是一个 R 值引用,我会完全清楚在调用 modifyCounter2() 后我不应该再使用该对象。

class Counter
{
public:
Counter() : value(new int32_t(0))
{
std::cout << "Counter()" << std::endl;
}

Counter(const Counter & other) : value(new int32_t(0))
{
std::cout << "Counter(const A &)" << std::endl;

*value = *other.value;
}

Counter(Counter && other)
{
std::cout << "Counter(Counter &&)" << std::endl;

value = other.value;
other.value = nullptr;
}

~Counter()
{
std::cout << "~Counter()" << std::endl;

if (value)
{
delete value;
}
}

Counter & operator=(Counter const & other)
{
std::cout << "operator=(const Counter &)" << std::endl;

*value = *other.value;

return *this;
}

Counter & operator=(Counter && other)
{
std::cout << "operator=(Counter &&)" << std::endl;

value = other.value;
other.value = nullptr;

return *this;
}

int32_t getValue()
{
return *value;
}

void setValue(int32_t newValue)
{
*value = newValue;
}

void increment()
{
(*value)++;
}

void decrement()
{
(*value)--;
}

private:
int32_t* value; // of course this could be implemented without a pointer, just for demonstration purposes!
};

void modifyCounter1(Counter & counter)
{
counter.increment();
counter.increment();
counter.increment();
counter.decrement();
}

void modifyCounter2(Counter & counter)
{
Counter newCounter = std::move(counter);
}

int main(int argc, char ** argv)
{
auto counter = Counter();

std::cout << "value: " << counter.getValue() << std::endl;

modifyCounter1(counter); // no surprises

std::cout << "value: " << counter.getValue() << std::endl;

modifyCounter2(counter); // surprise, surprise!

std::cout << "value: " << counter.getValue() << std::endl;

return 0;
}

最佳答案

是的,这令人惊讶且非常规。

如果您想允许 move ,惯例是按值传递。您可以根据需要从函数内部 std::move ,而调用者可以 std::move 进入参数,如果他们决定放弃所有权的话。

这种约定就是以这种方式命名 std::move 的概念的来源:促进明确没收所有权,表示意图。这就是为什么我们忍受这个名字,即使它具有误导性(std::move 并没有真正 move 任何东西)。

但你的方式是盗窃。 ;)

关于c++ - move 左值引用参数是不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56737499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com