Reputation: 9543
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.
Upvotes: 1
Views: 1829
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