4

As a follow up to my previous question (Variable Length Array Performance Implications (C/C++)), I am having a bit of trouble maintaining const correctness using the C system call writev(). Namely, it appears as though I have run into the exact same problem as this user did in C, although I am using C++:

https://codereview.stackexchange.com/questions/9547/casting-const-pointer-to-non-const-pointer-when-using-struct-iovec

Here's a snippet of my code:

int my_awesome_transmit_function(const uint8_t* const buffer, const size_t length) {
  // ... some stuff happens...
  struct iovec iov[2];
  iov[1].iov_base = buffer;  // compiler yells about this
  iov[1].iov_len = length;
  // ... some more code you don't care about
  writev(my_fd, iov, 2);
}

Given the solution presented from the CodeReview post, I have implemented the following change to the line that's giving me issues since I'd like to avoid the C-style cast:

iov[1].iov_base = const_cast<uint8_t*>(buffer);

Is this a valid way of using const cast? As far as I can tell, writev guarentees that the iov structure will not be modified (http://linux.die.net/man/2/writev). This blog post (http://blog.aaronballman.com/2011/06/when-should-you-use-const_cast/) leads me to believe that this is a valid usage (since I am never modifying the buffer), but I'd like to be certain since generally wherever I see const_cast or reinterpret_cast, I get a bit leery.

Thanks in advance for the help.

4

2 回答 2

3

是的,你的使用const_cast很好。

于 2013-10-01T17:37:46.990 回答
0

如果数组元素之一(永远)不会被修改,那么您可以将其声明为 const。

const struct iovec iov_c(buffer, length); // create a constructor for your struct! always neater than
                                          // assigning their members directly in code.

这假设您可以控制 writev(..) 的签名并且可以传入两个 iovec 指针。

如果没有,那里 const_cast 的用法看起来没问题。

于 2013-10-01T17:57:58.647 回答