eastern_strider said:
Hi,
Thanks for all replies. I've just given the sample code for
illustration and what I'm exactly doing is very similar to Greg's
example.
I'm using an external library function which accepts c-style strings as
argument. However, it just keeps a pointer to this argument. That is,
it DOES NOT actually copy it to an internal buffer. So my real use of
c_str() is just like:
MyClass::MyClass()
{
string str = "Hello";
BaseClass::add (str.c_str());
}
Now what "add" does is:
void BaseClass::add (const char *item)
{
item_ptr = item; // item_ptr is a const char* member of BaseClass
}
So this is the whole story. The question is, throughout the rest of the
program, does item_ptr continue to point to a valid location? I
believe I can ensure that explicitly by definining:
string* str = new string ("Hello");
inside my constructor. However, I've been wondering whether such an
explicit allocation is actually necessary in this case.
item_ptr is not valid. You'll need to manage the allocation of a
std::string. That does not mean you need a heap allocation. You can
keep a const std::string member in MyClass. You'll need to observe
what, if any, ctor is available for that BaseClass.
Now there are 2 issues you need to be aware of: copy ctors and
inheritence.
What follows is not neccessarily correct for you. You may prefer
overiding add(...).
#include <string>
class MyClass : public BaseClass
{
const std::string s_;
public:
MyClass(std::string s) : BaseClass() : s_(s)
{
add(s_.c_str());
}
MyClass(const MyClass& r_copy) : BaseClass(), s_(r_copy.s_) // const
{
add(s_.c_str()); // reseated pointer
}
};
If you need to copy an instance of MyClass, you certainly don't want
the BaseClass pointer (const char* item) to point to the original
instance. If you don't plan to copy at all, disable copy construction.
Better an error than a bug you'll regret.
class MyClass : public BaseClass
{
const std::string s_;
public:
MyClass(std::string s) : BaseClass() : s_(s)
{
add(s_.c_str());
}
MyClass(const MyClass& r_copy); // disabled
};
Lastly: inheritence.
Don't use pointers to BaseClass objects to store MyClass instances if
BaseClass does not have a virtual d~tor. I'm willing to bet that the
BaseClass is using a non-virtual compiler-generated ctor.
Finally, don't use pointers unless you absolutely have to. Always
prefer references.