gpt4 book ai didi

C++ : copy-and-swap idiom, 替代构造函数

转载 作者:行者123 更新时间:2023-11-28 07:28:51 35 4
gpt4 key购买 nike

注意:此问题遵循 a previous one , 我希望仍然可以将其作为一个新问题提出。

我正在尝试为树类实现“三个半大规则”( copy-and-swap 习语),它看起来像这样:

class Tree
{
friend void swap(Tree &first, Tree &second); // Swap function

public:
Tree(const double &a, const double &b, int depth); // Public constructor (derived from the default (private) constructor)
Tree(const Tree &other); // Copy constructor
~Tree(); // Destructor
Tree & operator=(Tree other); // Copy-assignement operator


private:
Tree(double *a, double *b, int depth, int maxDepth); // Default (private) constructor

double *a, *b;
int depth, maxDepth;
Tree *leftChild, *rightChild;
};

我一直在努力关注this guideline .这是我的复制赋值运算符的样子:

Tree & Tree::operator=(Tree other)
{
swap(*this, other);
return *this;
}

我很难让我的公共(public)构造函数工作。有人建议我做类似的事情:

Tree::Tree(const double &a, const double &b, int depth)
{
double aTemp(a), bTemp(b);
swap(*this, Tree(&aTemp, &bTemp, depth, depth));
}

我不确定这个想法是否可行。在任何情况下,我都会从编译器中得到以下错误:

invalid initialization of non-const reference of type 'Tree&' from an rvalue of type 'Tree'
in passing argument 2 of 'void swap(Tree&, Tree&)'

我尝试了以下想法,我认为它可行:

Tree::Tree(const double &a, const double &b, int depth)
{
double aTemp(a), bTemp(b);
*this = Tree(&aTemp, &bTemp, depth, depth);
}

但是好像也没有用。我认为问题在于,当我调用复制赋值运算符 (*this = Tree(&aTemp, &bTemp, depth, depth)) 时,应该调用复制构造函数(因为复制的参数-assignement operator is passed by value),但似乎这没有发生。我不明白为什么。

在此先感谢您的帮助!

最佳答案

invalid initialization of non-const reference of type 'Tree&' from an rvalue of type 'Tree' in passing argument 2 of 'void swap(Tree&, Tree&)'

C++ 不允许通过非const 引用传递匿名对象。目的是防止调用者意外丢弃写入引用参数的函数的结果。

你可以这样做:

Tree::Tree(const double &a, const double &b, int depth)
{
double aTemp(a), bTemp(b);
Tree temp(&aTemp, &bTemp, depth, depth);
swap(*this, temp);
}

But it does not seem to be working either. I think the problem is that when I call the copy-assignment operator (*this = Tree(&aTemp, &bTemp, depth, depth)), the copy constructor should be called (since the argument of the copy-assignement operator is passed by value), but it seems that this is not happening. I do not understand why.

您如何确定它不起作用?编译器可能会删除 拷贝以避免做不必要的工作。 ( That is why your copy-assignment operator takes the argument by value. )

顺便说一句,如果你的编译器支持 C++11,你可以使用 delegating constructors相反。

关于C++ : copy-and-swap idiom, 替代构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18139969/

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