【问题标题】:Function pointer becomes nullptr after constructor构造函数后函数指针变为nullptr
【发布时间】:2017-10-11 12:54:24
【问题描述】:

我有这个类,我需要在构造函数中传递一个函数指针并稍后调用该函数。实际上,我有2个指针。现在,其中一个函数仍然指向传递的函数,但在构造函数完成运行后,第二个函数变为nullptr。我已经尝试过调试并且......什么都没有。它只是在构造函数之后变为空。这是我的代码:

#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 为真。有人知道为什么会这样吗?

【问题讨论】:

  • 请编辑您的问题以包含minimal reproducible example
  • 旁注:函数定义后不需要;
  • [继续@JohnnyMopp 的评论] 但它在类定义之后需要的。
  • (TransmitBufferFunction*)transmitBuffer为什么要转换函数?
  • 你没有定义控制器类型的变量。

标签: c++ function pointers function-pointers


【解决方案1】:

好的,所以,哇。这里没有人会找到答案,因为我什至没有发布问题。我的问题是我忘记在复制构造函数中复制指针,我将它添加为一个向量(它会自动尝试复制它)。添加后,效果很好。很抱歉浪费了大家的时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 2012-09-27
    相关资源
    最近更新 更多