简体   繁体   中英

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:

  • How to pass a string literal to a function? Answers I could find: pass by value or pass it by const pointer or const reference. I don't want to pass it by value because it's slow (it's a profiler after all, accurate to microseconds). Const pointer/reference give a compiler error (or am I doing something wrong?)

  • How to assign it to a member function? The only solution I could find is making the member variable a pointer. Making it a non-pointer givers the error "field 'description' has incomplete type" (wtf does this mean?). Having it as a pointer doesn't work because it assigns a const to a non-const. Only a const pointer/reference seems to work.

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 ok 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 ok to store the char* pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM