const needed in function param list

closed account (zwA4jE8b)
Before using const for _src I had excluded it. This did not allow me to use
string.c_str() as a source.

Can anyone tell me why const is needed? I noticed that c_str() is a const function. Does that play into it?

void* memc0py(void* _dst, const void* _src, size_t _sz)
closed account (3hM2Nwbp)
If I recall, std::string::c_str() returns a const char*. You'll need the const qualifier unless you const_cast it away, but const_cast is almost always a bad idea from what I've seen.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<string>

void* memc0py1(void* _dst, const void* _src, size_t _sz);

void* memc0py2(void* _dst, void* _src, size_t _sz);

int main()
{
  std::string hello = "Hello";
  const char* cString = hello.c_str();
  char* notConst = const_cast<char*>(cString); // <- IDK why the standard allows for it.
  void* somePointer;
  memc0py1(somePointer, cString, 3);
  memc0py2(somePointer, nonConst, 3);
  return 0xBADC0DE;
}
Last edited on
c_str() returns a const char*, so it *should* be convertible to a const void*...

1
2
3
4
5
6
7
8
void f(const void* p) {
	std::cout<<(const char*)(p);
}

int main() {
	std::string str = "argle";
	f(str.c_str());
}


Seems to work for me...
closed account (zwA4jE8b)
Thanks, and yes firedraco, the above function prototype works, it was previously when I did not include const that I noticed it did not work.
Oh duh, I misread the question. >_> Glad you got your answer anyway.
Topic archived. No new replies allowed.