Carbon
Carbon

Reputation: 3973

Change constructor order of operations?

I have the following sample code, and the copy assignment is doing something I don't want - it's first constructing the new samp(6), then copying it to z, then destroying the new samp(6) it built. Is there a way to change the constructors such that = acts like a pointer, destroying the originally constructed samp(5) and replacing it with the new samp(6), calling the destructor on samp(5), rather than 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;
}

Upvotes: 0

Views: 73

Answers (2)

M.M
M.M

Reputation: 141613

Maybe pointer semantics is what you want:

#include <memory>

// ...

    auto z = std::make_unique<samp>(5);
    z = std::make_unique<samp>(6);   // dest5

    std::cout << z->m_a << '\n';     // 6

Although if you are coming to C++ from a language where object names are object references, it may be better to get used to C++ value semantics instead of trying to replicate object references :)

Upvotes: 1

RichN
RichN

Reputation: 372

operator= is a member of your object so the this pointer is available. Also, assignment means the target of the assignment should change. Your version is creating a new object, but leaving the target alone. See if this does what you want:

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

Upvotes: 0

Related Questions