更改操作的构造函数顺序

Change constructor order of operations?

本文关键字:构造函数 顺序 操作      更新时间:2023-10-16

我有以下示例代码,复制赋值正在做一些我不想要的事情 - 它首先构造新的 samp(6(,然后将其复制到 z,然后销毁它构建的新 samp(6(。有没有办法改变构造函数,使 = 像指针一样,销毁最初构造的 samp(5( 并用新的 samp(6( 替换它,在 samp(5( 上调用析构函数,而不是 samp(6(?

#include <iostream>
class samp
{
public:
    samp(int a)
    {
        m_a = a;
        std::cout << "cons" <<m_a << std::endl;
    }
    int m_a;
    samp(const samp& other)
    {
        std::cout << "copy" << m_a << std::endl;
        m_a = other.m_a;
    }
    samp& operator= (const samp& other)
    {
        std::cout << "assg" << m_a << std::endl;
        samp* z =new samp(other.m_a);
        return *z;
    }
    ~samp()
    {
        std::cout << "dest" <<m_a<< std::endl;
    }
};
int main()
{
    samp z(5);
    z = samp(6);
    std::cout << z.m_a << std::endl;
    return 0;
}

也许指针语义是你想要的:

#include <memory>
// ...
    auto z = std::make_unique<samp>(5);
    z = std::make_unique<samp>(6);   // dest5
    std::cout << z->m_a << 'n';     // 6

尽管如果您从对象名称是对象引用的语言C++,最好习惯于C++值语义,而不是尝试复制对象引用:)

operator=

对象的成员,因此this指针可用。此外,分配意味着分配的目标应该改变。您的版本正在创建一个新对象,但保留目标。看看这是否符合您的要求:

samp& operator= (const samp& other)
{
    m_a = other.m_a;
    return *this;
}