use a pointer in operation with non pointer - c++

I'm quite new to C++ and I don't understand very well the pointers yet.
this is ok, I have 2 non pointer object:
Vec2D A(0, 0), B(10, 10);
Vec2D C = A-B;
but if one is a pointer?
Vec2D::minus(Vec2D B) {
Vec2D that = Vec2D(this->x(), this->y());
return that-B;
}
So the question: how can I use the pointer this with - operation with B?
And also, I don't understand how many object are constructed in my methods and how can I optimize memory consumption passing some reference..

If I got your question correctly.. "this is a pointer, how can I operate on it and other pointers using methods that require a non-pointer?"
You use the dereference operator *
Example:
Vec2D that = *this;
To answer your second question:
an object is created to pass it as a parameter of minus
an object is created by Vec2D(this->x(), this->y()) (but will be probably erased away as a temp by a good optimizing compiler)
an object is created by you on the stack (that)
depending on how you implemented them, and on how good your compiler is, you may create another object in your copy constructor/operator=
an object (or more) may be created by your operator- in that-B
an object is created to be returned (only one, not two, as return value optimization is done by all compliers AFAIK)
How can you optimize it? Use references...
Vec2D Vec2D::minus(const Vec2D& B) {
return that-*this;
}
And implement operator- on Vec2D to use refereces too...
In general, pass parameters as (const) references.
Obviously, you cannot do the same for the return value (try, the compiler will complain..); there are techniques for these as well (especially in CG/games, with vectors, I have seen object pools used a lot; for those returning a reference/pointer is actually possible, but it is rather advanced stuff)

The "this" pointer is an auto-generated pointer to the object that contains the method being called.
If you call A.minus(B), the "this" pointer points to A.

Related

Memory Management in C++

I'm trying to test how and where the data is located and destroyed. For the example code below:
A new point is created and returned with NewCartesian method. I know that it should be stored in heap. When it's pushed back into the vector, does the memory of the points content is copied into a new Point structure? Or is it stored as a reference the this pointer?
When the point is created, when is it destroyed? Do I need to destroy the points when I'm done with it? Or are they destroyed when they are not usefuly anymore? For example, if main was another function, the vector would not be useful when it's finished.
Depending on the answers above, when is it good to use the reference of objects? Should I use Point& p or Point p for the return of Point::NewCartesian?
#define _USE_MATH_DEFINES
#include <iostream>
#include <cmath>
using namespace std;
struct Point {
private:
Point(float x, float y) : x(x), y(y) {}
public:
float x, y;
static Point NewCartesian(float x, float y) {
return{ x, y };
}
};
int main()
{
vector<Point> vectorPoint;
for (int i = 0; i < 10000; i++) {
Point& p = Point::NewCartesian(5, 10);
vectorPoint.push_back( p );
// vectorPoint.push_back( Point::NewCartesian(5, 10) );
Point& p2 = Point::NewPolar(5, M_PI_4);
}
cout << "deneme" << endl;
getchar();
return 0;
}
Thank you for your help,
Cheers,
... I know that it should be stored in heap.
Firstly, please read this explanation of why it's preferable to talk about automatic and dynamic object lifetimes, rather than stack/heap.
Secondly, that object is neither dynamically-allocated nor on the heap. You can tell because dynamic allocation uses a new-expression, or a library function like malloc, calloc or possibly mmap. If you don't have any of those (and you almost never should), it's not dynamic.
You're returning something by value, so that thing's lifetime is definitely automatic.
When the point is created, when is it destroyed?
If you write the full set of copy/move constructors and assignment operators, plus a destructor, you can simply set breakpoints in them in the debugger and see where they get invoked. Or, have them all print their this pointer and input arguments (ie, the source object being moved or copied from).
However, since we know the object is automatic, the answer is easy - when it goes out of scope.
Should I use Point& p or Point p for the return of Point::NewCartesian?
Definitely the second: the first returns a reference to an object with automatic lifetime in the scope of the NewCartesian function, meaning the objected referred to is already dead by the time the caller gets the reference.
Finally, this code
Point& p = Point::NewCartesian(5, 10);
is weird - it makes it hard to determine the lifetime of the Point referred to by p by reading the code. It could be some static/global/other object with dynamic lifetime to which NewCartesian returns a reference, or (as is actually the case) you could be binding a reference to an anonymous temporary. There's no benefit to writing it this way instead of
Point p = Point::NewCartesian(5, 10);
or just passing the temporary straight to push_back as in your commented code.
As an aside, the design of Point is very odd. It has public data members, but a private constructor, and a public static method that just calls the constructor. You could omit the constructor and static method entirely and just use aggregate initialization, or omit the static method and make the constructor public.
1a. No, it's on the stack, but read the answer by Useless, why the terms stack and heap are not the best choice.
1b. It gets copied when you call push_back.
2 . It's destroyed immediately after being created, because it only exists within the scope of the NewCartesian call and for the duration of the return being evaluated.
3a. You use a reference whenever you have a valid instance and want to pass it to a function without creating a copy. Specifically the function should have a reference parameter.
3b. You should use Point p, not Point& p, because right now you get a dangling reference to an object that doesn't exist anymore (see 2.)
As pointed out by Steven W. Klassen in the comments, your best option is the code that you have commented out: vectorPoint.push_back( Point::NewCartesian(5, 10) );. Passing the call to NewCartesian directly into push_back without making a separate local copy, allows the compiler to optimize it so that the memory is constructed exactly where push_back wants it and avoiding any intermediate memory allocations or copies. (Or more technically, it allows it to use the move operator.)

Passing pointers between objects in c++

I want to ask about passing pointers between functions or between objects or returning them .. I heard that passing or returning pointers in general (whether they point to an array or an object or whatever they are pointing at) isn't safe and the output isn't guaranteed.
now I've tried it and so far everything seems OK but I don't want my project to work by accident .. so can someone explain to me why not to pass or return pointers and what are the suggested solution (for example, what if I want to modify the same object (say object1) in a function in another object (function func in object2))?
also, I read in a tutorial that everything in c++ is pass by value? isn't passing pointers is called pass by reference?
Thanx everybody.
I want to ask about passing pointers between functions or between objects or returning them .. I heard that passing or returning pointers in general (whether they point to an array or an object or whatever they are pointing at) isn't safe and the output isn't guaranteed.
Where did you get that from? In general, it's not true and of course you can pass around pointers.
The tricky thing is managing ownership of (heap-allocated) objects, since somewhere you have to release the memory again. In other words: When you allocate memory with new, you will have to free it again with delete.
Example:
A* function1(A* a) {
return a;
}
B* function2(B* b) {
return new B(b);
}
function1 returns an existing pointer. Whoever owned the A object passed in will also own the returned one, as it is the same. This needs to be documented since this knowledge is essential for using function1!
function2 creates a new object of class B by coping its input argument. Whoever calls function2 will own the returned object and will be responsible to delete it when it's done. Again, this needs to be documented!
also, I read in a tutorial that everything in c++ is pass by value? isn't passing pointers is called pass by reference?
Technically, passing pointers is pass-by-value since the pointer itself gets copied. But since a pointer is a "reference type", you essentially get pass-by-reference with that.
Note that C++ also knows references (int&), which really is pass-by-reference.
Well, the honest answer is that people sometimes mean different things when they say "pass by reference".
But generally, when people say "pass by reference", they mean this:
void readInt(int &a) {
cin >> a;
}
int a;
readInt(a);
cout << a;
And "pass by pointer" would be this:
void readInt(int *a) {
cin >> *a;
}
int a;
readInt(&a);
cout << a;
Ultimately, you can use pointers for everything that references are used for (they other way around is mostly true).
Some people like references because they can use the . operator, like they normally do. Others prefer pointers because they are explicit.
Note that pointers are older than references (C does not have references), so C libraries will use pointers exclusively.
Most people (I think) use references when they can (like in your hypothetical example). The nice thing is that type safety will stop you if you confuse references and pointers.

unique_ptr and polymorphism

I have some code that currently uses raw pointers, and I want to change to smart pointers. This helps cleanup the code in various ways. Anyway, I have factory methods that return objects and its the caller's responsibility to manager them. Ownership isn't shared and so I figure unique_ptr would be suitable. The objects I return generally all derive from a single base class, Object.
For example,
class Object { ... };
class Number : public Object { ... };
class String : public Object { ... };
std::unique_ptr<Number> State::NewNumber(double value)
{
return std::unique_ptr<Number>(new Number(this, value));
}
std::unique_ptr<String> State::NewString(const char* value)
{
return std::unique_ptr<String>(new String(this, value));
}
The objects returned quite often need to be passed to another function, which operates on objects of type Object (the base class). Without any smart pointers the code is like this.
void Push(const Object* object) { ... } // push simply pushes the value contained by object onto a stack, which makes a copy of the value
Number* number = NewNumber(5);
Push(number);
When converting this code to use unique_ptrs I've run into issues with polymorphism. Initially I decided to simply change the definition of Push to use unique_ptrs too, but this generates compile errors when trying to use derived types. I could allocate objects as the base type, like
std::unique_ptr<Object> number = NewNumber(5);
and pass those to Push - which of course works. However I often need to call methods on the derived type. In the end I decided to make Push operate on a pointer to the object stored by the unique_ptr.
void Push(const Object* object) { ... }
std::unique_ptr<Object> number = NewNumber(5);
Push(number.get());
Now, to the reason for posting. I'm wanting to know if this is the normal way to solve the problem I had? Is it better to have Push operate on the unique_ptr vs the object itself? If so how does one solve the polymorphism issues? I would assume that simply casting the ptrs wouldn't work. Is it common to need to get the underlying pointer from a smart pointer?
Thanks, sorry if the question isn't clear (just let me know).
edit: I think my Push function was a bit ambiguous. It makes a copy of the underlying value and doesn't actually modify, nor store, the input object.
Initially I decided to simply change the definition of Push to use
unique_ptrs too, but this generates compile errors when trying to use
derived types.
You likely did not correctly deal with uniqueness.
void push(std::unique_ptr<int>);
int main() {
std::unique_ptr<int> i;
push(i); // Illegal: tries to copy i.
}
If this compiled, it would trivially break the invariant of unique_ptr, that only one unique_ptr owns an object, because both i and the local argument in push would own that int, so it is illegal. unique_ptr is move only, it's not copyable. It has nothing to do with derived to base conversion, which unique_ptr handles completely correctly.
If push owns the object, then use std::move to move it there. If it doesn't, then use a raw pointer or reference, because that's what you use for a non-owning alias.
Well, if your functions operate on the (pointed to) object itself and don't need its address, neither take any ownership, and, as I guess, always need a valid object (fail when passed a nullptr), why do they take pointers at all?
Do it properly and make them take references:
void Push(const Object& object) { ... }
Then the calling code looks exactly the same for raw and smart pointers:
auto number = NewNumber(5);
Push(*number);
EDIT: But of course no matter if using references or pointers, don't make Push take a std::unique_ptr if it doesn't take ownership of the passed object (which would make it steal the ownership from the passed pointer). Or in general don't use owning pointers when the pointed to object is not to be owned, std::shared_ptr isn't anything different in this regard and is as worse a choice as a std::unique_ptr for Push's parameter if there is no ownership to be taken by Push.
If Push does not take owenrship, it should probably take reference instead of pointer. And most probably a const one. So you'll have
Push(*number);
Now that's obviously only valid if Push isn't going to keep the pointer anywhere past it's return. If it does I suspect you should try to rethink the ownership first.
Here's a polymorphism example using unique pointer:
vector<unique_ptr<ICreature>> creatures;
creatures.emplace_back(new Human);
creatures.emplace_back(new Fish);
unique_ptr<vector<string>> pLog(new vector<string>());
for each (auto& creature in creatures)
{
auto state = creature->Move(*pLog);
}

Trying to store an object in an array but then how to call that object's methods?

I'm not a very experienced c++ coder and this has me stumped. I am passing a object (created elsewhere) to a function, I want to be able to store that object in some array and then run through the array to call a function on that object. Here is some pseudo code:
void AddObject(T& object) {
object.action(); // this works
T* objectList = NULL;
// T gets allocated (not shown here) ...
T[0] = object;
T[0].action(); // this doesn't work
}
I know the object is passing correctly, because the first call to object.action() does what it should. But when I store object in the array, then try to invoke action() it causes a big crash.
Likely my problem is that I simply tinkered with the .'s and *'s until it compiled, T[0].action() compliles but crashes at runtime.
The simplest answer to your question is that you must declare your container correctly and you must define an appropriate assigment operator for your class. Working as closely as possible from your example:
typedef class MyActionableClass T;
T* getGlobalPointer();
void AddInstance(T const& objInstance)
{
T* arrayFromElsewhere = getGlobalPointer();
//ok, now at this point we have a reference to an object instance
//and a pointer which we assume is at the base of an array of T **objects**
//whose first element we don't mind losing
//**copy** the instance we've received
arrayFromElsewhere[0] = objInstance;
//now invoke the action() method on our **copy**
arrayFromElsewhere[0].action();
}
Note the signature change to const reference which emphasizes that we are going to copy the original object and not change it in any way.
Also note carefully that arrayFromElsewhere[0].action() is NOT the same as objInstance.action() because you have made a copy — action() is being invoked in a different context, no matter how similar.
While it is obvious you have condensed, the condensation makes the reason for doing this much less obvious — specifying, for instance, that you want to maintain an array of callback objects would make a better case for “needing” this capability. It is also a poor choice to use “T” like you did because this tends to imply template usage to most experienced C++ programmers.
The thing that is most likely causing your “unexplained” crash is that assignment operator; if you don't define one the compiler will automatically generate one that works as a bitwise copy — almost certainly not what you want if your class is anything other than a collection of simple data types (POD).
For this to work properly on a class of any complexity you will likely need to define a deep copy or use reference counting; in C++ it is almost always a poor choice to let the compiler create any of ctor, dtor, or assignment for you.
And, of course, it would be a good idea to use standard containers rather than the simple array mechanism you implied by your example. In that case you should probably also define a default ctor, a virtual dtor, and a copy ctor because of the assumptions made by containers and algorithms.
If, in fact, you do not want to create a copy of your object but want, instead, to invoke action() on the original object but from within an array, then you will need an array of pointers instead. Again working closely to your original example:
typedef class MyActionableClass T;
T** getGlobalPointer();
void AddInstance(T& objInstance)
{
T** arrayFromElsewhere = getGlobalPointer();
//ok, now at this point we have a reference to an object instance
//and a pointer which we assume is at the base of an array of T **pointers**
//whose first element we don't mind losing
//**reference** the instance we've received by saving its address
arrayFromElsewhere[0] = &objInstance;
//now invoke the action() method on **the original instance**
arrayFromElsewhere[0]->action();
}
Note closely that arrayFromElsewhere is now an array of pointers to objects instead of an array of actual objects.
Note that I dropped the const modifier in this case because I don’t know if action() is a const method — with a name like that I am assuming not…
Note carefully the ampersand (address-of) operator being used in the assignment.
Note also the new syntax for invoking the action() method by using the pointer-to operator.
Finally be advised that using standard containers of pointers is fraught with memory-leak peril, but typically not nearly as dangerous as using naked arrays :-/
I'm surprised it compiles. You declare an array, objectList of 8 pointers to T. Then you assign T[0] = object;. That's not what you want, what you want is one of
T objectList[8];
objectList[0] = object;
objectList[0].action();
or
T *objectList[8];
objectList[0] = &object;
objectList[0]->action();
Now I'm waiting for a C++ expert to explain why your code compiled, I'm really curious.
You can put the object either into a dynamic or a static array:
#include <vector> // dynamic
#include <array> // static
void AddObject(T const & t)
{
std::array<T, 12> arr;
std::vector<T> v;
arr[0] = t;
v.push_back(t);
arr[0].action();
v[0].action();
}
This doesn't really make a lot of sense, though; you would usually have defined your array somewhere else, outside the function.

Is it wrong to dereference a pointer to get a reference?

I'd much prefer to use references everywhere but the moment you use an STL container you have to use pointers unless you really want to pass complex types by value. And I feel dirty converting back to a reference, it just seems wrong.
Is it?
To clarify...
MyType *pObj = ...
MyType &obj = *pObj;
Isn't this 'dirty', since you can (even if only in theory since you'd check it first) dereference a NULL pointer?
EDIT: Oh, and you don't know if the objects were dynamically created or not.
Ensure that the pointer is not NULL before you try to convert the pointer to a reference, and that the object will remain in scope as long as your reference does (or remain allocated, in reference to the heap), and you'll be okay, and morally clean :)
Initialising a reference with a dereferenced pointer is absolutely fine, nothing wrong with it whatsoever. If p is a pointer, and if dereferencing it is valid (so it's not null, for instance), then *p is the object it points to. You can bind a reference to that object just like you bind a reference to any object. Obviously, you must make sure the reference doesn't outlive the object (like any reference).
So for example, suppose that I am passed a pointer to an array of objects. It could just as well be an iterator pair, or a vector of objects, or a map of objects, but I'll use an array for simplicity. Each object has a function, order, returning an integer. I am to call the bar function once on each object, in order of increasing order value:
void bar(Foo &f) {
// does something
}
bool by_order(Foo *lhs, Foo *rhs) {
return lhs->order() < rhs->order();
}
void call_bar_in_order(Foo *array, int count) {
std::vector<Foo*> vec(count); // vector of pointers
for (int i = 0; i < count; ++i) vec[i] = &(array[i]);
std::sort(vec.begin(), vec.end(), by_order);
for (int i = 0; i < count; ++i) bar(*vec[i]);
}
The reference that my example has initialized is a function parameter rather than a variable directly, but I could just have validly done:
for (int i = 0; i < count; ++i) {
Foo &f = *vec[i];
bar(f);
}
Obviously a vector<Foo> would be incorrect, since then I would be calling bar on a copy of each object in order, not on each object in order. bar takes a non-const reference, so quite aside from performance or anything else, that clearly would be wrong if bar modifies the input.
A vector of smart pointers, or a boost pointer vector, would also be wrong, since I don't own the objects in the array and certainly must not free them. Sorting the original array might also be disallowed, or for that matter impossible if it's a map rather than an array.
No. How else could you implement operator=? You have to dereference this in order to return a reference to yourself.
Note though that I'd still store the items in the STL container by value -- unless your object is huge, overhead of heap allocations is going to mean you're using more storage, and are less efficient, than you would be if you just stored the item by value.
My answer doesn't directly address your initial concern, but it appears you encounter this problem because you have an STL container that stores pointer types.
Boost provides the ptr_container library to address these types of situations. For instance, a ptr_vector internally stores pointers to types, but returns references through its interface. Note that this implies that the container owns the pointer to the instance and will manage its deletion.
Here is a quick example to demonstrate this notion.
#include <string>
#include <boost/ptr_container/ptr_vector.hpp>
void foo()
{
boost::ptr_vector<std::string> strings;
strings.push_back(new std::string("hello world!"));
strings.push_back(new std::string());
const std::string& helloWorld(strings[0]);
std::string& empty(strings[1]);
}
I'd much prefer to use references everywhere but the moment you use an STL container you have to use pointers unless you really want to pass complex types by value.
Just to be clear: STL containers were designed to support certain semantics ("value semantics"), such as "items in the container can be copied around." Since references aren't rebindable, they don't support value semantics (i.e., try creating a std::vector<int&> or std::list<double&>). You are correct that you cannot put references in STL containers.
Generally, if you're using references instead of plain objects you're either using base classes and want to avoid slicing, or you're trying to avoid copying. And, yes, this means that if you want to store the items in an STL container, then you're going to need to use pointers to avoid slicing and/or copying.
And, yes, the following is legit (although in this case, not very useful):
#include <iostream>
#include <vector>
// note signature, inside this function, i is an int&
// normally I would pass a const reference, but you can't add
// a "const* int" to a "std::vector<int*>"
void add_to_vector(std::vector<int*>& v, int& i)
{
v.push_back(&i);
}
int main()
{
int x = 5;
std::vector<int*> pointers_to_ints;
// x is passed by reference
// NOTE: this line could have simply been "pointers_to_ints.push_back(&x)"
// I simply wanted to demonstrate (in the body of add_to_vector) that
// taking the address of a reference returns the address of the object the
// reference refers to.
add_to_vector(pointers_to_ints, x);
// get the pointer to x out of the container
int* pointer_to_x = pointers_to_ints[0];
// dereference the pointer and initialize a reference with it
int& ref_to_x = *pointer_to_x;
// use the reference to change the original value (in this case, to change x)
ref_to_x = 42;
// show that x changed
std::cout << x << '\n';
}
Oh, and you don't know if the objects were dynamically created or not.
That's not important. In the above sample, x is on the stack and we store a pointer to x in the pointers_to_vectors. Sure, pointers_to_vectors uses a dynamically-allocated array internally (and delete[]s that array when the vector goes out of scope), but that array holds the pointers, not the pointed-to things. When pointers_to_ints falls out of scope, the internal int*[] is delete[]-ed, but the int*s are not deleted.
This, in fact, makes using pointers with STL containers hard, because the STL containers won't manage the lifetime of the pointed-to objects. You may want to look at Boost's pointer containers library. Otherwise, you'll either (1) want to use STL containers of smart pointers (like boost:shared_ptr which is legal for STL containers) or (2) manage the lifetime of the pointed-to objects some other way. You may already be doing (2).
If you want the container to actually contain objects that are dynamically allocated, you shouldn't be using raw pointers. Use unique_ptr or whatever similar type is appropriate.
There's nothing wrong with it, but please be aware that on machine-code level a reference is usually the same as a pointer. So, usually the pointer isn't really dereferenced (no memory access) when assigned to a reference.
So in real life the reference can be 0 and the crash occurs when using the reference - what can happen much later than its assignemt.
Of course what happens exactly heavily depends on compiler version and hardware platform as well as compiler options and the exact usage of the reference.
Officially the behaviour of dereferencing a 0-Pointer is undefined and thus anything can happen. This anything includes that it may crash immediately, but also that it may crash much later or never.
So always make sure that you never assign a 0-Pointer to a reference - bugs likes this are very hard to find.
Edit: Made the "usually" italic and added paragraph about official "undefined" behaviour.