Search code examples
c++classpointersconstructor

Why am I getting "Write Access Violation: this was 0x7FF895E32BB3" when trying to reference *this in a class constructor?


I have a program which requires one class (B) to be made in a class's (A) constructor with a reference to the class (A) that made it passed into it's (B) constructor. Rubbish description I know but I don't know how better to word it.

I'm getting the error at runtime and it's pointing to B's constructor where the reference to A is assigned to a variable.

Here's the smallest code I could make that reproduced the error:

class A;

class B {
public:
    B();
    B(A &a);
    ~B();
private:
    A *m_a;
};

class A {
public:
    A();
    A(int x);
    ~A();
private:
    B m_b;
};

B::B() {}

B::B(A &a) {
    *m_a = a; //           Exception thrown: write access violation.
} //                       this->m_a was 0x7FF895E32BB3.

B::~B() {}

A::A() {}

A::A(int x) {
    m_b = B(*this);
}

A::~A() {}

int main() {
    A temp = A(10);
}

I've tried adding and removing default constructors and I've tried to make a separate function solely for the m_b = B(*this) line because other posts similar to this seemed to suggest that *this wasn't working because the object *this was referring to hadn't fully been made yet.

Call stack:

[External Code]
main() Line 40
A::A(int x) Line 32
B::B(A & a) Line 24

I hope the names A and B aren't too short to make the code difficult to read. I don't know what I'd call them otherwise.

I don't really know how to describe what my aim is without going into tons of detail about my original program which I don't think would be appropriate.

Thanks in advance to anyone that helps and sorry for the strange code - I'm pretty new to C++


Solution

  • *m_a = a;
    

    This takes the existing pointer, m_a, and the object a gets assigned to whatever m_a is already pointing to.

    Unfortunately, this m_a is a completely uninitialized pointer, it's random garbage, and this comprises undefined behavior.

    It is unclear what exactly the intent of the shown code is. Perhaps the intent here is to set m_a to the address of a, or

    m_a=&a;
    

    It's important to understand when working with pointers in C++ that pointers and the objects they point to are different, independent entities. Each one can be assigned to, and it is important to understand the fundamental differences.

    This should address the immediate undefined behavior here, but this overall approach is somewhat error prone and will often result in undefined behavior elesewhere, but as far as the reason for the crash, this is it.