mercredi 30 octobre 2019

returning a class from a metod gives wrong values for class variables

My header file contains a class that holds a Boolean and a string

#ifndef RESULT_P
#define RESULT_P

#include <string>
#include <utility>

class MyResult {

public:
    MyResult() = default;
    MyResult( const bool& ok, std::string  msg) : ok_(ok), msg_(std::move(msg)) {}
    explicit MyResult(bool ok) : ok_(ok) {}
    explicit MyResult(std::string msg) : ok_(false), msg_(std::move(msg)) {}

    bool ok() const {
        return ok_;
    }

    void ok(bool ok) {
        ok_ = ok;
    }

    const std::string &msg() const {
        return msg_;
    }

    void msg(const std::string &msg) {
        msg_ = msg;
    }

private:
    bool ok_ { false };
    std::string msg_;

};

#endif

I am using the MyResult(std::string) constructor to create a result that takes by default false on the ok_ method variable.

I am calling

auto result = do_something()

The method do somethings looks like this

   MyResult do_something() {

      if ( something ) {
         //code    } else {
          return MyResult("something wrong happened");    
      }
    }

So returns false and a string. When this method returns and I am calling

cout << result.ok() << endl;

it prints false!!! instead of true. What is wrong?

Aucun commentaire:

Enregistrer un commentaire