函数指针在构造函数后变为 nullptr
Function pointer becomes nullptr after constructor
我有这个class,我需要在构造函数中传入一个函数指针并稍后调用该函数。实际上,我有 2 个指针。现在,其中一个函数仍然指向传递的函数,但第二个函数在构造函数完成 运行 后变为 nullptr
。我试过调试......什么都没有。它只是在构造函数之后变为 null。这是我的代码:
#include <vector>
#include <cstdint>
typedef void (TransmitBufferFunction)(void*, std::vector<uint8_t>);
typedef std::vector<uint8_t> (ReceiveBufferFunction)(void*, int);
class Controller {
public:
TransmitBufferFunction* transmitBuffer = nullptr;
ReceiveBufferFunction* receiveBuffer = nullptr;
Controller(TransmitBufferFunction* sendBuffer, ReceiveBufferFunction* receiveBuffer);
};
#include "controller.hpp"
Controller::Controller(TransmitBufferFunction* _transmitBuffer, ReceiveBufferFunction* _receiveBuffer) {
transmitBuffer = _transmitBuffer;
receiveBuffer = _receiveBuffer;
};
我这样使用它:
#include "controller.hpp"
#include <iostream>
void transmitBuffer(void* _handle, std::vector<uint8_t> buffer) {
// ...
};
std::vector<uint8_t> receiveBuffer(void* _handle, int size) {
std::vector<uint8_t> buf;
// ...
return buf;
};
int main(int argc, char** argv) {
Controller controller = Controller(&transmitBuffer, &receiveBuffer);
std::cout << (controller.transmitBuffer != nullptr) << std::endl;
std::cout << (controller.receiveBuffer != nullptr) << std::endl;
return 0;
};
这输出:
1
0
它们都应为 1 表示真。有人知道为什么会这样吗?
好的,所以,哇。这里没有人会找到答案,因为我什至没有发布问题。我的问题是我忘记在复制构造函数中复制指针,并且我正在向它添加一个向量(它会自动尝试复制它)。添加后,工作正常。抱歉浪费了大家的时间。
我有这个class,我需要在构造函数中传入一个函数指针并稍后调用该函数。实际上,我有 2 个指针。现在,其中一个函数仍然指向传递的函数,但第二个函数在构造函数完成 运行 后变为 nullptr
。我试过调试......什么都没有。它只是在构造函数之后变为 null。这是我的代码:
#include <vector>
#include <cstdint>
typedef void (TransmitBufferFunction)(void*, std::vector<uint8_t>);
typedef std::vector<uint8_t> (ReceiveBufferFunction)(void*, int);
class Controller {
public:
TransmitBufferFunction* transmitBuffer = nullptr;
ReceiveBufferFunction* receiveBuffer = nullptr;
Controller(TransmitBufferFunction* sendBuffer, ReceiveBufferFunction* receiveBuffer);
};
#include "controller.hpp"
Controller::Controller(TransmitBufferFunction* _transmitBuffer, ReceiveBufferFunction* _receiveBuffer) {
transmitBuffer = _transmitBuffer;
receiveBuffer = _receiveBuffer;
};
我这样使用它:
#include "controller.hpp"
#include <iostream>
void transmitBuffer(void* _handle, std::vector<uint8_t> buffer) {
// ...
};
std::vector<uint8_t> receiveBuffer(void* _handle, int size) {
std::vector<uint8_t> buf;
// ...
return buf;
};
int main(int argc, char** argv) {
Controller controller = Controller(&transmitBuffer, &receiveBuffer);
std::cout << (controller.transmitBuffer != nullptr) << std::endl;
std::cout << (controller.receiveBuffer != nullptr) << std::endl;
return 0;
};
这输出:
1
0
它们都应为 1 表示真。有人知道为什么会这样吗?
好的,所以,哇。这里没有人会找到答案,因为我什至没有发布问题。我的问题是我忘记在复制构造函数中复制指针,并且我正在向它添加一个向量(它会自动尝试复制它)。添加后,工作正常。抱歉浪费了大家的时间。