Use std::addressof to instead of plain '&'.#2254
Use std::addressof to instead of plain '&'.#2254gennadiycivil merged 2 commits intogoogle:masterfrom
Conversation
Otherwise the code won't compile if the '&' operater is overloaded and return something that cannot be casted to void *.
|
Thanks for your pull request. It looks like this may be your first contribution to a Google open source project (if not, look below for help). Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA). 📝 Please visit https://cla.developers.google.com/ to sign. Once you've signed (or fixed any issues), please reply here (e.g. What to do if you already signed the CLAIndividual signers
Corporate signers
ℹ️ Googlers: Go here for more info. |
|
I signed it! |
|
CLAs look good, thanks! ℹ️ Googlers: Go here for more info. |
|
Thank your for this contribution. Could you please elaborate and provide more information , do you have a concrete example? |
|
Here is a minimal example of what I'm trying to do. Basically I want to create a synthetic pointer class that can be used as an iterator over a buffer of fixed size strings. And I created a synthetic reference class, which has the overloaded #include <gtest/gtest.h>
class string_ref;
/**
* This is a synthetic pointer to a fixed size string.
*/
class string_ptr {
public:
string_ptr(const char *data, size_t size) : data_(data), size_(size) {}
string_ptr &operator++() noexcept {
data_ += size_;
return *this;
}
string_ref operator*() const noexcept;
private:
const char *data_;
size_t size_;
};
/**
* This is a synthetic reference of a fixed size string.
*/
class string_ref {
public:
string_ref(const char *data, size_t size) : data_(data), size_(size) {}
string_ptr operator&() const noexcept { return {data_, size_}; }
bool operator==(const char *s) const noexcept {
if (size_ > 0 && data_[size_ - 1] != 0) {
return std::string_view(data_, size_) == std::string_view(s);
} else {
return std::string_view(data_) == std::string_view(s);
}
}
private:
const char *data_;
size_t size_;
};
string_ref string_ptr::operator*() const noexcept {
return {data_, size_};
}
TEST(string_ref, compare) {
const char *s = "alex\0davidjohn\0";
string_ptr ptr(s, 5);
// EXPECT_EQ(*ptr, "alex"); // I wish I can do this, but it won't compile
EXPECT_TRUE(*ptr == "alex");
++ptr;
// EXPECT_EQ(*ptr, "david");
EXPECT_TRUE(*ptr == "david");
++ptr;
// EXPECT_EQ(*ptr, "john");
EXPECT_TRUE(*ptr == "john");
} |
|
@chaoran Thank you for this example. Could you please also add a unit test and we can proceed after that. |
|
Unit test added. |
|
248165482 |
PiperOrigin-RevId: 248759825
|
note that we moved the code around a bit not to create entire new file. |
Otherwise the code won't compile if the '&' operater is overloaded and
return something that cannot be casted to void *.