c++ - 如何使用对象指针而不是对象来编写赋值运算符/复制构造函数?

标签 c++ assignment-operator

我看到很多解释如何为对象编写赋值运算符/复制构造函数的示例,但是,当涉及到对象指针时,我感到很吃力。附上示例代码。

我希望 test2(test1) 调用复制构造函数,但它似乎没有调用用户指定的复制构造函数。

#include <vector>
#include <iostream>
#include <memory>

template <class fd>
class node
{
    public:
//    private:
        std::vector <fd> data_point;
        std::shared_ptr< node <fd> > left;
        std::shared_ptr< node <fd> > right;
        bool collision;

//    public:
        node(std::vector <fd> &data, bool level=0);
        ~node();
        node(const node <fd> &old);
        void check_point();
};

template <class fd>
node <fd>::node(std::vector <fd> &data, bool level)
{
    if (level) throw std::invalid_argument( "Error->Duplicate data" );
    else
    {
        data_point = data;
        left = nullptr;
        right = nullptr;
        collision = level;
    }
}

template <class fd>
node <fd>::~node() {}

template <class fd>
node <fd>::node(const node <fd> &old)
{
    std::cout<<"Copy constructor called"<<std::endl;
//    this->data_point = old.data_point;
//    this->left = new node <fd> (old.left);
//    this->right = new node <fd> (old.right);
//    this->collision = old.collision;
}

template <class fd>
void node <fd>::check_point()
{
    if (this == nullptr)
    {
        std::cout<<"It's a leaf node with None"<<std::endl;
    }
    else
    {
        for (int dim=0; dim<this->data_point.size(); dim++)
        {
            std::cout<<data_point[dim]<<" ";
        }
        std::cout<<std::endl;
    }
}

int main()
{
    std::vector <double> data;
    data = {50};
    std::shared_ptr <node <double> > test1 = std::make_shared <node <double> > (data);
//    std::cout << typeid(test1).name() << std::endl;
    test1->check_point();//Prints 50.Expected
    std::shared_ptr <node <double> > test2(test1);//Expecting copyconstructor call for deep copy
    test1->data_point = {75};//Changing value
    test2->check_point();//If deep copy happened, value would not change. Default copy constructor does not shallow copy and hence value does not change.
    test1->check_point();
    return 0;
}

如果您能解释一下这是如何完成的,那就太好了。

最佳答案

触发上述程序中复制构造函数的使用的最小更改:

//std::shared_ptr <node <double> > test2(test1);//Expecting copyconstructor call for deep copy
std::shared_ptr <node <double> > test2 = std::make_shared <node <double> >(*test1);

新行将取消引用 test1 的指针,并将其传递给构造 test2 的构造函数,从而调用复制构造函数。

新输出:

50
Copy constructor called

75

关于c++ - 如何使用对象指针而不是对象来编写赋值运算符/复制构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41511744/

相关文章:

c++ - 重载 '+' 以添加两个矩阵

javascript - = 符号(单个)在条件中有何用途?

c++ - RAII 和赋值

c++ - 为什么内置赋值返回一个非 const 引用而不是 C++ 中的 const 引用?

r - 涉及因子的数据表赋值

c++ - 杀死无符号/有符号比较错误

c++ - 如何使旧版本的 clang 对 atomic 的默认异常规范感到满意

c++ - OpenMP 嵌套循环索引依赖

c++ - 路径规划——多个目的地

C++默认复制和赋值运算符