Home > Software engineering >  Wondering if my shared member is working?
Wondering if my shared member is working?

Time:11-03

I have a shared_ptr I'm trying to use in two functions of a class, not sure if I have it working right. The shared object class I'm using might be broken, but it's not my repo so I'm wanting to check if it's my issue on my end.

myHeader.h

#include "otherClass.h"

namespace myheader {
class myClass : {
public: 
  // Constructor
  myClass();
  ~myClass() = default;

  bool incomingMessage();

private: 
  std::shared_ptr<randomnamespace::OtherClass> otherClass_ = std::make_shared<randomnamespace::OtherClass>();
};
};

myClass.cpp

#include "myHeader.h"

using namespace myheader;

myClass::myClass() 
  :
  otherClass_()

{
  otherClass_->setConfiguration(x);
  std::cout << "Debug: Initialized";
}

bool myClass::incomingMessage() {
  otherClass_->sendData();
  std::cout << "Debug: Data sent";
  return true;
}

I'm wondering if it seems to be shared correctly?

I've tried running this(compiling works), and the otherClass_->() calls don't work in either place. Have tried testing both individually with the other commented out, and I don't get the Debug print's after the otherClass_-> calls.

CodePudding user response:

You try to initialize otherClass_ twice:

  • once with a default member initializer:

      std::shared_ptr<randomnamespace::OtherClass> otherClass_ = std::make_shared<randomnamespace::OtherClass>();
    
  • once with a mem-initializer in the constructor:

      myClass::myClass(): otherClass_()
    

The standard says that when this happens, the default member initializer is ignored and the member is initialized according to the mem-initializer in ctor. Here that means that you initialize otherclass_ to be an empty shared pointer...

You should remove the offending initialization in ctor:

myClass::myClass() 
{
  otherClass_->init();
  std::cout << "Debug: Initialized";
}

CodePudding user response:

Main question

myClass::myClass() 
  :
  otherClass_()

This initializes your member (otherClass_) with nothing from the constructor.

This will override the definition of

 std::shared_ptr<randomnamespace::OtherClass> otherClass_ = std::make_shared<randomnamespace::OtherClass>();

where you already have initialized it before correctly.

Solution:

  1. Remove : otherClass_() from the constructor.
  2. Remove the initialization from otherClass_ and use :otherClass_(std::make_shared<randomnamespace::OtherClass>()) to initialize it from the constructor.

Other notes

Remove the colon after class myClass : {.

To implement incomingMessage() you need

bool myClass::incomingMessage() {

Other than that, I don't see that you return otherClass_ anywhere or pass it as a parameter. You don't share it, you only use it. It looks like you can use a unique_ptr.

  •  Tags:  
  • c
  • Related