c++ - 这个指针在C++中突然变成了0x0

标签 c++ pointers constructor null

我有一个(显然)非常简单的类初始化,有两个构造函数,当我想创建一个新的 Friendship 时,第一个参数的 this 指针具有适当的指针值,但第二个没有。

我会在代码中更好地解释 - 这是我的构造函数之一:

Friendship::Friendship(const User &u1, const User &u2){
    *user1 = u1;
    *user2 = u2;
}

当我在我的测试类中这样做时:

bool Test::insertFriendship(User *user1, User *user2) {
    bool friendshipExists = verifyFriendship(user1, user2);

    if(!friendshipExists) {
        friendships.push_back(new Friendship(*user1, *user2)); // this is a ptr_vector container
        return true;
    }
    return false;
}

它在 push_back 行给我一个 EXC_BAD_ACCESS 错误,因为显然 user1 的“this”指针在到达构造函数时有效并且指向一个有效的内存地址,但是当它去执行 user2 时,' this' user2 的指针指向 0x0 并且它失败了,因为这基本上是在到达 operator = overload 时尝试重新引用 NULL。

例如:当它试图创建一个新的友元时:

this->user1 的内存地址 = 0x100100b20 this->user2 的内存地址 = 0x0 - 错误!

同时

u1 的内存地址 = 0x7fff5fbff900 u2 的内存地址 = 0x7fff5fbff898

我的意思是,这些 u1 和 u2 内存地址是有效的,所以当我尝试这样做时为什么它不起作用:

*user1 = u1; //works cos this is 0x100100b20
*user2 = u2; // fails cos this is 0x0 even though u2 is a valid mem address!

有人知道为什么会出现这种奇怪的行为吗?即使我在我的 push_back 中切换 user1 和 user2,它仍然不会在第二个上工作。总是那个讨厌的第二个永远不起作用。

啊,这是我的 Friendship 头文件,没什么太复杂的。

#include "User.h"

#ifndef Friendship_h
#define Friendship_h

class Friendship {
    friend class Test;
protected:
    User *user1;
    User *user2;

public:
    Friendship(const User &u1, const User &u2);
    Friendship(const Friendship &a);
    ~Friendship();
};

#endif

最佳答案

Friendship::Friendship(const User &u1, const User &u2)
{
    *user1 = u1;
    *user2 = u2;
}

因为 user1user2 还没有初始化,你还不能解引用它们。我想你的意思是:

Friendship::Friendship(const User &u1, const User &u2)
{
    user1 = &u1;
    user2 = &u2;
}

关于c++ - 这个指针在C++中突然变成了0x0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8145501/

相关文章:

无法用函数指针填充 double 组

c++ - 为什么析构函数调用比构造函数调用多

c++ - 关于 C++ 中自定义对象的构造函数/析构函数和新建/删除运算符

c++ - 重写虚方法时无法返回派生类指针

C 另一个指针的指针

c++ - 从无符号整数中减去有符号整数

抛弃指向 const 的指针数组中的常量性,以及有关 C 的其他问题

c++ - 初始化 const 对象中的引用

c++ - 二值图像角点检测

c++ - 我可以读取 open_memstream() 生成的流吗?