Mark Jeronimus
Mark Jeronimus

Reputation: 9543

Passing string literal to function and assign to member variable

This might be a newbie question, but I cannot solve this problem. I can solve either the former or latter problem separately but not at the same time.

I have a class with a string member, and a function to set it. I want to pass a literal to the function.

class Profiler
{
private:
    std::string description;
    //snip

public:
    //snip
    void startJob(const std::string &desc);
};

void Profiler::startJob(const string &desc) {
    //snip
    description = desc;
}

and I want (Actually need) to use it like this:

profiler.startJob("2 preprocess: 1 cvConvertScale");

The problems are:

Upvotes: 1

Views: 1829

Answers (1)

dsign
dsign

Reputation: 12700

Pass by reference, store by value, include the header:

#include <string>

class Profiler {
  private:
    std::string description;
    //snip

  public:
    //snip
    void startJob(const std::string &desc);
};

void Profiler::startJob(const string &desc) {
  //snip
  description = desc;
}

Storing by value is o.k. as long as you don't modify the original string. If you don't do that, they will share memory and there won't be an inefficient copy.Still, in this case you will get the characters copied to the buffer controlled by std::string.

I don't think it be possible to store the pointer to a literal-char* as an instance of std::string, although it would be o.k. to store the char* pointer.

Upvotes: 2

Related Questions