I'm coding c++11.
In a class A, I have a member variable "member" which is defined as
vector<OtherClass> member; // A's member variable
I would like to serialize A ( so I want to all the data type in OtherClass contained in the vector ) into file in binary format so I defined a function write as follows.
void A::write(ostream& os){ // A's function for outputting A
os.write(reinterpret_cast<const char*>( &(member.size()) ), sizeof(member.size()));
}
But compiler said lvalue required as unary '&' operand.
How can I fix it without creating a temporary object such as long size=member.size() in the write function?
The problem is &(member.size()) - you're not assigning size()'s return value and trying to take the address of it (it may not even have an address).
But no idea why you're calling size here anyway you need the start address of the actual data: member.data() (or if you dont have C++11 &member[0])
"How can I fix it without creating a temporary object"
You can't. You want to use &, which takes the address of an object. No object, no address. It's really that simple.
Note that your long size = member.size() idea doesn't create a temporary variable. That's an ordinary variable.
Related
I have got a class that has overloaded unary operator&. The objects of that type were created using new, so address of variable was accessible but now I need to use static object. Is it possible to get its address?
In C++11 or later, std::addressof(object), declared by the <memory> header.
Historically, it was more grotesque, especially if you wanted to deal with const and volatile qualifiers correctly. One possibility used by Boost's implementation of addressof is
reinterpret_cast<T*>(
&const_cast<char&>(
reinterpret_cast<const volatile char &>(object)))
first adding qualifers while converting to char& so that reinterpret_cast would work however object were qualified; then removing them so that the final conversion would work; then finally taking the address and converting that to the correct type. As long as T has the same qualifiers as object (which it will as a template parameter deduced from object), the resulting pointer will be correctly qualified.
Since C++11, you may use the function std::addressof
I have two programs that communicate over the D-Bus. In one of the there is a function that takes two parameters namely const char* data and int size and in another one I have a function that returns a value of the type unsigned char. I place a function call in the first program like this function((char*)program2->function().value(), 1) but i get the warning cast to pointer from integer of different size [-Wint-to-pointer-cast]. how should i resolve this warning? also I'm using Qt libraries.
EDIT:
actually in the function that takes the const char* and int I append the data to a QByteArray which accepts const char* and a size of type int in it's constructor as provided by Qt and the other program is supposed to return a number in the range 0-255 hence the unsinged char. If what I'm doing is wrong what's the best way to obtain the desired result?
Also call to program2->function invokes the following:
inline QDBusPendingReply<uchar> type()
{
QList<QVariant> argumentList;
return asyncCallWithArgumentList(QLatin1String("type"), argumentList);
}
this class has a function called value() which invokes:
inline typename Select<0>::Type value() const
{
return argumentAt<0>();
}
NOTE: my main purpose of this question was to find out a way to create a reference to the returned result of calling a function defined within the proxy class not how to convert it to something acceptable for creation of a QByteArray so please stop adding unrelated tags like QByteArray or QtCore etc.
What you need is the address of the data... which would look like
function2(& program2->function().value(), 1);
and would be perfectly safe, since the lifetime of the temporary variable is until the end of the complete expression, which is long enough1 for function2 to use it.
Unfortunately, you can't use the & address-of operator on an rvalue. But there is a workaround, since you can bind a const lvalue reference to an rvalue, and you want a pointer to const data anyway:
template<T>
const T* get_addr(const T& v) { return &v; }
function2( get_addr(program2->function().value()), 1 );
If you get a signed-vs-unsigned, mismatch, try
function2( get_addr<char>(program2->function().value()), 1 );
Of course this is a lot of work just to avoid giving the variable a name, as Captain Obvlious has done.
1 Unless function2 saves that pointer for later, but if it does then you shouldn't be using a local variable to hold the value either, but pay very close attention to object lifetime.
I do not think what you are doing is safe, hence your code might not work at all. If your function() is returning an "unsigned char", its going to make a copy of it and return it. At the same time your other function() is taking a "const char*". I suggest to modify your program2->function() to return a "char *".
Converting an integer to a pointer is not a really good idea especially if you don't know why the conversion is necessary and what exactly it does. It looks like the conversion isn't even necessary and you really need a solution to properly call the function instead of fixing the cast warning. From the code and description you provided it appears you want to send a single byte returned by the call to program2->function(). Since the value returned by this function is an rvalue you can't directly take it's address. Instead you can to store it in a variable and then pass a pointer to that instead. Something like the code below should let you do what you want.
char value = program2->function();
function(&value, 1);
In a function, how to you assign this a new value?
You can assign the object this points at:
*this = XY;
But you can't assign the direct value of this:
this = &XY; // Error: Expression is not assignable
You can't.
9.3.2 The this pointer [class.this]
1 In the body of a non-static (9.3) member function, the keyword this is a prvalue expression whose value
is the address of the object for which the function is called. [...] (emphasis & link mine)
You can modify the object this points to, which is *this. For example:
struct X
{
int x;
void foo()
{
this->x =3;
}
};
The method modifies the object itself, but something like this = new X is illegal.
Long ago, before the first C++ standard has been published, some compiler implementations allowed you to write the following code inside a constructor:
this = malloc(sizeof(MyClass)); // <<== No longer allowed
The technique served as the only way to control allocation of class of objects. This practice has been prohibited by the standard, because overloading of the operator new has solved the problem that used to be tackled by assignments to this.
You can't. If you feel the need to do this perhaps you should be writing a static method taking a class pointer as it's first parameter.
You cannot assign value to this pointer. If you try to assign the value to the this somthing like this = &a it would result in illegal expression
You can not.
"this" is a hidden argument to every member function of a class and its type for an object of Class X is X* const. This clearly means that you can not assign a new vale to "this" as it is defined as a const. You can however modify the value pointed to by this. Refer http://www.geeksforgeeks.org/this-pointer-in-c/ for more details.
I'm currently reading through Accelerated C++ and I realized I don't really understand how & works in function signatures.
int* ptr=#
means that ptr now holds the address to num, but what does that mean?
void DoSomething(string& str)
from what I understand that is a pass by reference of a variable (which means passing the address) but when I do
void DoSomething(string& str)
{
string copy=str;
}
what it creates is a copy of str. What I thought it would do is raise an error since I'm trying to assign a pointer to a variable.
What is happening here? And what is the meaning of using * and & in function calls?
A reference is not a pointer, they're different although they serve similar purpose.
You can think of a reference as an alias to another variable, i.e. the second variable having the same address. It doesn't contain address itself, it just references the same portion of memory as the variable it's initialized from.
So
string s = "Hello, wordl";
string* p = &s; // Here you get an address of s
string& r = s; // Here, r is a reference to s
s = "Hello, world"; // corrected
assert( s == *p ); // this should be familiar to you, dereferencing a pointer
assert( s == r ); // this will always be true, they are twins, or the same thing rather
string copy1 = *p; // this is to make a copy using a pointer
string copy = r; // this is what you saw, hope now you understand it better.
The & character in C++ is dual purpose. It can mean (at least)
Take the address of a value
Declare a reference to a type
The use you're referring to in the function signature is an instance of #2. The parameter string& str is a reference to a string instance. This is not just limited to function signatures, it can occur in method bodies as well.
void Example() {
string s1 = "example";
string& s2 = s1; // s2 is now a reference to s1
}
I would recommend checking out the C++ FAQ entry on references as it's a good introduction to them.
https://isocpp.org/wiki/faq/references
You shouldn't know anything about pointers until you get to chapter 10 of Accelerated C++ !
A reference creates another name, an alias, for something that exists elsewhere. That's it. There are no hidden pointers or addresses involved. Don't look behind the curtain!
Think of a guy named Robert
guy Robert;
Sometimes you may want to call him Bob
guy& Bob = Robert;
Now Bob and Robert both refer to the same guy. You don't get his address (or phone number), just another name for the same thing.
In your function
void DoSomething(string& str)
{
string copy=str;
}
it works exactly the same, str is another name for some string that exists somewhere else.
Don't bother with how that happens, just think of a reference as a name for some object.
The compiler has to figure out how to connect the names, you don't have to.
In the case of assigning variables (ie, int* ptr = &value), using the ampersand will return the address of your variable (in this case, address of value).
In function parameters, using the ampersand means you're passing access, or reference, to the same physical area in memory of the variable (if you don't use it, a copy is sent instead). If you use an asterisk as part of the parameter, you're specifying that you're passing a variable pointer, which will achieve almost the same thing. The difference here is that with an ampersand you'll have direct access to the variable via the name, but if you pass a pointer, you'll have to deference that pointer to get and manipulate the actual value:
void increase1(int &value) {
value++;
}
void increase2(int *value) {
(*value)++;
}
void increase3(int value) {
value++;
}
Note that increase3 does nothing to the original value you pass it because only a copy is sent:
int main() {
int number = 5;
increase1(number);
increase2(&number);
increase3(number);
return 0;
}
The value of number at the end of the 3 function calls is 7, not 8.
It's a reference which allows the function to modify the passed string, unlike a normal string parameter where modification would not affect the string passed to the function.
You will often see a parameter of type const string& which is done for performance purposes as a reference internally doesn't create a copy of the string.
int* ptr=#
1st case: Since ptr is a memory and it stores the address of a variable. The & operator returns the address of num in memory.
void DoSomething(string& str)
2nd case: The ampersand operator is used to show that the variable is being passed by reference and can be changed by the function.
So Basically the & operator has 2 functions depending on the context.
While pass by reference may be implemented by the compiler by passing the address as a pointer, semantically it has nothing to do with addresses or pointers. in simple terms it is merely an alias for a variable.
C++ has a lot of cases where syntax is reused in different contexts with different semantics and this is one of those cases.
In the case of:
int* ptr=#
you are declaring a variable named ptr with a type of an int * (int pointer), and setting its value to the "address of the variable num" (&num). The "addressof" operator (&) returns a pointer.
In the case of:
void DoSomething(string& str)
you are declaring the first parameter of the DoSomething() method to be of type "reference to string". Effectively, this is the C++ way of defining "pass-by-reference".
Note that while the & operator operates similarly in these cases, it's not acting in the same way. Specifically, when used as an operator, you're telling the compiler to take the address of the variable specified; when used in a method signature, you're telling the compiler that the argument is a reference. And note as well, that the "argument as a reference" bit is different from having an argument that is a pointer; the reference argument (&) gets dereferenced automatically, and there's never any exposure to the method as to where the underlying data is stored; with a pointer argument, you're still passing by reference, but you're exposing to the method where the variable is stored, and potentially exposing problems if the method fails to do a dereference (which happens more often than you might think).
You're inexplicitly copy-constructing copy from str. Yes, str is a reference, but that doesn't mean you can't construct another object from it. In c++, the & operator means one of 3 things -
When you're defining a normal reference variable, you create an alias for an object.
When you use it in a function paramater, it is passed by reference - you are also making an alias of an object, as apposed to a copy. You don't notice any difference in this case, because it basically is the object you passed to it. It does make a difference when the objects you pass contain pointers etc.
The last (and mostly irrelevent to your case) meaning of & is the bitwise AND.
Another way to think about a reference (albeit slightly incorrect) is syntactic sugar for a dereferenced pointer.
What does address operator mean.
say in the method below.
what should be passed in the method as parameter value of integer or the address of an integer variable.
void func1(int&)// method declaration
void func1(int& inNumber)//method definition
{
//some code
}
That’s not the address operator – it’s the reference type character. This means that for any type T, T& is a reference to T. It’s an unlucky coincidence that this happens to be the same character as the address operator.
You can pass normal objects to this method. No need to take any further action. Read up on references in your favourite C++ book.
There is no address-of operator in your code - the ampersand is being used to declare a reference. Which C++ text book are you using that does not cover this?
In this case the function takes a reference to an int which is denoted by the int &inNumber.
The function is called as if you were calling it with the value:
int x = 2;
func1(x);
From the perspective of the caller, this looks exactly the same as a pass by value function, though in the case of the reference the function may indeed change the value of x.
That's not an address operator. In a declaration, the & means it's a reference.
You can think of references as pointers that you don't have to dereference.* You can just say inNumber = 5; (instead of *inNumber = 5;) and the effect will be visible outside the function.
* Note: References are not just "pointers that you don't have to dereference". It just helps to think of them in that way, sometimes.
its called as reference in c++
http://en.wikipedia.org/wiki/Reference_(C%2B%2B)