Dynamic allocation as a parameter, so to speak? [closed] - c++

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Assume we have a vector of Cursor object pointers. A cursor object is constructed with a single int parameter. So will this syntax work?
vector<cursor*> cursors;
cursors.push_back(new cursor(4));
Or do I have to do it as:
cursor* tempCursor = new cursor(4);
cursors.push_back(tempCursor);

Despite the fact that you may not have tried this here's an explanation of what's going on:
when you create a new cursor object it returns a new cursor object. When you use a push_back function it pushes an object back on a vector. So, when you create a new object inside the push_back it evaluates that function which returns a new cursor which then gets pushed back.
Basically its all about return values and evaluations.

You will leak memory if you do this as you are stating and don't clean it up afterwards.
A better way would be to use a shared_ptr.
The code would look like this
cursors.push_back(std::make_shared<cursor>(4));
It's a little hard to understand exactly what you're trying to accomplish though.
As mentioned below in the comments by #cat-plus-plus, unique_ptr should be used unless you explicitly want the object shared elsewhere, the code then would look like the following:
cursors.push_back(std::unique_ptr<cursor>(new cursor(4)));

It will work, but chances are pretty good that you're better off doing something else. Absent a really good reason to do otherwise, I'd consider making it a vector of cursors (instead of pointers to cursors). In this case, you can just do something like:
std::vector<cursor> cursors;
cursors.push_back(4); // or cursors.emplace_back(4);
This generally improves programmer efficiency by automating memory management, and improves code efficiency by eliminating unnecessary levels of indirection.

Related

C/C++ The purpose of static const local variable [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
In C and C++, what is the advantage of making a local const variable static? Assuming the initialization does not use other variables, is there any difference between preserving the value between calls, and setting the same constant value each call?
Could a valid C compiler ignore the static?
In C++, it avoids the construction/destruction between calls, but could there be any other benefit?
It doesn't take up stack-space may be a benefit if you have something like:
static const double table[fairly_large_number] = { .... };
Obviously, cost of construction can also be substantial enough that if the function is called a lot, there's good value in only constructing the object once.
Yes, and it is huge: a semantic benefit.
When you put const, you don't just mean the compiler shouldn't let you modify the variable. You make a bolder statement to whoever reads the code later: this won't ever change. Not even by a side effect where you give this variable as a pointer to another function.
Also, the compiler can take advantage of that new information and optimize it away in some situations, depending on the specific type you are dealing with.
(to be clear, I'm speaking here about const vs. non-const, not static vs. non-static.)
Edit: This SO answer is very informative too.

Is it possible to create variables during runtime in c++ [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Is it possible to create a new variable for a function everytime the function is called? I was considering making a huge array and just using a different block for each time a function is called but I would prefer to create variables on demand instead, is this possible in c++?
Example:
A user types asdf and clicks save, setting off the savetext function
void savetext(textvariable)
{
static int //(this variable name should somehow become asdf) = somedata;
return;
}
If you have something that, for example, adds things to an array, then vector is the right solution. The vector class will automatically grow as you need it, using the push_back function to add things to itself.
The vector class acts largely as an array that grows as you need it to, so it's very easy to use.
Every time you enter a function, all variables in it are new. There's no need to explicitly create variables unless you need objects that live longer than your function, or you don't know how many you need.

Strategy Pattern at runtime? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have a strategy pattern, and would like to run it in a main loop in a game for example. The problem is there will be a memory leak If I'm not deleting the instance, and I also would like to use that instance somewhere else. How can I deal with memory allocation/deallocation in a strategy pattern.
CompressionContext *ctx = new CompressionContext();
//we could assume context is already set by preferences
ctx->setCompressionStrategy(new ZipCompressionStrategy());
//get a list of files
ctx->createArchive(fileList);
Use an std::shared_ptr<CompressionContextBase> instead of a CompressionContextBase* (i.e. a raw pointer).
Edit: This is just a suggestion, based on the information you provided, there may be other smart pointer implementations with different semantics, such as e.g. unique_ptr, which might be more suited. As #akappa suggests, you may want to read up on the topic more, to make a better decision -- again, based on the information in the question, you probably want a shared_ptr but there might be additional considerations you omitted.

Using const on local variables [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
Similar to this question, what are the pro/cons to using const local variables like in this answer?
Personally, I like to use const for any declared object (I'm not sure the word "variable" applies) unless I'm actually going to modify it. It documents to the reader that the value of the object is always going to be whatever it was initialized to, which can make the code easier to follow and analyze.
(It can also help the compiler in some cases, but most compilers, when invoked in optimizing mode, are smart enough to notice that the object is never modified. And if you invoke the compiler in non-optimizing mode, you're telling it that you don't care much about performance.)
In fact, if I were going to design my own language, all declared objects would be const (read-only) by default unless you explicitly mark them as modifiable.

How to fix heap corruption in c/c++? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
This is a further question for my previous one here.
Is there a general solution for this?
Fix all dangling pointers
Fix all buffer overflows
Use pointers only where they are really needed
Reading your original post I'm not 100% you are facing a heap-corruption and you really hope you don't because if you would this is one of the most tricky errors to track down and AFAIK there are no solutions that always work.
However, if you are positive its a heap-corruption and you are on the windows platform you could try out the tool gflags. This advanced debugging tools allow you to install a debug heap manager in order to make it possible to find certain kinds of heap corruptions. One of the neat options it has is to make each allocation in it's own page or to write protect the heap datastructures. This makes it easier to pinpoint the exact location of the heap-corruption. It sucks lots of memory and CPU though.
Another tip if you are using Visual Studio is that if you manage to find that something is corrupting the data after a certain point of time and you wish to find the code that corrupts the data you can use Data Breakpoint to break whenever someone changes the data in question.
I wish you good luck.
Adding to swegi's answer I would check all your C++ constructors and all C initializations. Transform all dynamic C++ constructors (those where you put the init code in the function body) into static ones (where you initialize with the special constructor syntax). And be sure that you init all pointers and pointer members to 0. For C, I would initialize all variables.
Then, on unix I would use valgrind, usually this is quite good in finding all access violations and if you compile with all debugging options on it is able to trace it to the source line. There should be something similar on windows, too.