|
-
July 13th, 2010, 07:40 AM
#1
allow literal string only
is it possible to create a constructor that takes as parameter ONLY a literal string?
I have a class that is designed to be used with a literal string only. This requirement allows us to simplify what the constructor does by assumption that we can 'store' the string only by copying the pointer, without having to copy the contents of the string.
Code:
class Foo
{
public:
Foo(LPCSTR lpsz) m_str(lpsz) {}
LPCSTR m_str;
}
This requirement can't be changed, this is both a performance issue, and security issue in that the string is assumed to be located in readonly memory.
There's currently a big warning plastered on the function prototype saying to use it ony with a literal, but this has been "overlooked" several times in the past resulting in hard to track down issues.
Ideal would be if we can get the compiler to simply reject everything other than a literal.
so in short:
Code:
Foo("this is ok");
static const char sz[] = "this is also ok";
Foo(sz);
char sz2[] = "Modifiable strings are not ok";
Foo(sz2); // should give compiler error
char sz3[255];
strcpy(sz3, "C-style string is not ok");
Foo(sz3); // should give compile error
CString str("MFC string is not ok");
Foo(str); // should give compile error
std::string str2("STL string is not ok");
Foo(str2); // should give compile error
Is this possible ?
Last edited by OReubens; July 13th, 2010 at 07:42 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|