在构造函数中使用关键字“ this”时定义副本构造函数

时间:2019-02-01 14:53:24

标签: c++ class c++11 copy-constructor ros

在定义类# Check images. Display if differ # $file_path = "C:\Files" $last_state = "last_state.json" # Check last_state.json. If false - create new empty file. If (!(Test-Path $last_state)) { New-Item $last_state -ItemType file | Out-Null } $last_state_obj = Get-Content $last_state | ConvertFrom-Json # Get files list and hash. Also you can use -Recurse option Get-ChildItem $file_path -Filter *.* | Foreach-Object { if (!$_.PSIsContainer) { $current_state += @($_ | Get-FileHash -Algorithm MD5) } } # Compare hash ForEach ($current_file in $current_state) { if (($last_state_obj | where {$current_file.Path -eq $_.Path}).Hash -ne $current_file.Hash) { $changed += @($current_file) } } # Display changed files $changed # Save new hash to last_state.json $current_state | ConvertTo-JSON | Out-File $last_state 的副本构造函数时遇到困难。类TextListener使用TextListener关键字绑定方法callback。请查看下面的完整代码:

this

为了测试上述类,我创建了它的一个实例,该实例可以正常工作。但是,当我创建一个新实例并将该实例分配给新实例时,新实例不起作用。下面是代码片段:

#include <iostream>
#include <ros/ros.h>
#include <std_msgs/String.h>

class TextListener {
 private:
  std::string _text;
  ros::Subscriber _subscriber;

 public:
  TextListener() {
    std::cout << "[" << this << "] deafult constructor called" << std::endl;
  }

  TextListener(const TextListener &other)
      : _subscriber(other._subscriber), _text(other._text) {
    std::cout << "[" << this << "] copy constructor called" << std::endl;
  }

  TextListener &operator=(const TextListener &other) {
    std::cout << "[" << this << "] copy assignment called" << std::endl;
    _subscriber = other._subscriber;
    _text = other._text;
    return *this;
  }

  TextListener(ros::NodeHandle &nh, const std::string &topicName) {
    std::cout << "[" << this << "] constructor called" << std::endl;
    _subscriber = nh.subscribe(topicName, 1, &TextListener::callback, this);
  }

  void callback(const std_msgs::String::ConstPtr &msg) { _text = msg->data; }

  std::string &getText() { return _text; }

  ~TextListener() {
    std::cout << "[" << this << "] destructor called" << std::endl;
  }
};

方法int main(int argc, char **argv) { ros::init(argc, argv, "tet_listener"); ros::NodeHandle nh; std::string topicName = "chatter"; TextListener listener(nh, topicName); TextListener copyListener = listener; ros::Rate loop_rate(1); while (ros::ok()) { ROS_INFO("I heard: [%s]", copyListener.getText().c_str()); ros::spinOnce(); loop_rate.sleep(); } return 0; } 没有任何值。参见下面的输出:

getText()

我想复制构造函数缺少某些内容。 在构造函数中使用关键字“ this”时如何定义副本构造函数?

1 个答案:

答案 0 :(得分:3)

您需要两个Subscriber,一个通知原始TextListener对象,另一个通知副本TextListener

您实际上确实有两个订户,但是由于TextListener副本中的一个是原始订户的副本,因此它们都更新了原始TextListener的_text成员。

除了在TextListener中保留对NodeHandle的引用,让复制构造函数重新订阅NodeHandle而不是复制原始对象的订阅(即调用原始对象的回调)之外,我没有更好的方法。