question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
308,061 | 308,075 | Virtualization in Super Class Constructor | I was of the opinion that virtualization doesnt work in the super class constructor as per the design of OOP. For example, consider the following C# code.
using System;
namespace Problem
{
public class BaseClass
{
public BaseClass()
{
Console.WriteLine("Hello, World!");
... | In native C++, the program works as expected: you get the call to the base class version of the virtual function within the base class constructor. At the time of the constructor call, only the base class and its virtual functions exist, so you get the lowest-level version of the virtual function defined at the time. T... |
308,276 | 308,318 | Can I call a constructor from another constructor (do constructor chaining) in C++? | As a C# developer I'm used to running through constructors:
class Test {
public Test() {
DoSomething();
}
public Test(int count) : this() {
DoSomethingWithCount(count);
}
public Test(int count, string name) : this(count) {
DoSomethingWithName(name);
}
}
Is there a way ... | C++11: Yes!
C++11 and onwards has this same feature (called delegating constructors).
The syntax is slightly different from C#:
class Foo {
public:
Foo(char x, int y) {}
Foo(int y) : Foo('a', y) {}
};
C++03: No
Unfortunately, there's no way to do this in C++03, but there are two ways of simulating this:
You can... |
308,277 | 308,286 | What are the consequences of ignoring: warning: unused parameter | I am working on a C++ project and I noticed that we have a number of warnings about unused parameters.
What effect could it have if these warnings are ignored?
| The function with an unused parameter may have a real bug in the following cases:
There is an output parameter, which is not being assigned or written into, resulting in undefined value for the caller.
One of parameters is a callback function pointer, which you must invoke and forget to do so. May happen if there is a... |
308,279 | 308,724 | C++ strings: [] vs. * | Been thinking, what's the difference between declaring a variable with [] or * ? The way I see it:
char *str = new char[100];
char str2[] = "Hi world!";
.. should be the main difference, though Im unsure if you can do something like
char *str = "Hi all";
.. since the pointer should the reference to a static member, w... | Let's look into it (for the following, note char const and const char are the same in C++):
String literals and char *
"hello" is an array of 6 const characters: char const[6]. As every array, it can convert implicitly to a pointer to its first element: char const * s = "hello"; For compatibility with C code, C++ allow... |
308,307 | 308,346 | Setting file version number in Visual Studio 2005 C++ | Can anyone point me in the right direction how to configure Visual Studio 2005 with our C++ console project how we can include a 'File Version' in the details section of the file properties.
I've tried resource files without any luck. This is with a C++ project just for clarification, and big thank you for the guys you... | If you are talking about unmanaged c++, you need to add a version resource to the project.
right-click on the project, choose add - Resource.... Choose Version and press new.
There you can enter all info you need.
|
308,364 | 308,383 | C++ bitfield packing with bools | I've just done a test with bitfields, and the results are surprising me.
class test1 {
public:
bool test_a:1;
bool test_b:1;
bool test_c:1;
bool test_d:1;
bool test_e:1;
bool test_f:1;
bool test_g:1;
bool test_h:1;
};
class test2 {
public:
int test_a:1;
int test_b:1;
int te... | your compiler has arranged all of the members of test3 on integer size boundaries. Once a block has been used for a given type (integer bit-field, or boolean bit-field), the compiler does not allocate any further bit fields of a different type until the next boundary.
I doubt it is a bug. It probably has something to d... |
308,450 | 308,657 | Netbeans or Eclipse for C++? | I'm currently working on a pet project and need to do C++ development on Windows, Mac, Linux, and Solaris, and I've narrowed it down to Netbeans and Eclipse, so I was wonderig which is more solid as a C++ editor. I just need solid editing, good autocompletion for templated code ad external libraries, and project file m... | I haven't used NetBeans, but Eclipse CDT (C Developer Tools, which includes C++), especially with the latest version, is really quite excellent:
Syntax checking and spell checking
Syntax highlighting that distinguishes between library calls and your function calls and between local and member variables and is even app... |
308,477 | 308,661 | C++ Smart Pointer performance | How much do using smart pointers, particularly boost::shared_ptr cost more compared to bare pointers in terms of time and memory? Is using bare pointers better for performance intensive parts of gaming/embedded systems? Would you recommend using bare pointers or smart pointers for performance intensive components?
| Dereferencing smart pointers is typically trivial, certainly for boost in release mode. All boost checks are at compile-time. (Smart pointers could in theory do smart stuff across threads). This still leaves a lot of other operations. Nicola mentioned construction, copying and destruction. This is not the complete set,... |
308,619 | 308,632 | STL Vector comparison issue | With a vector defined as std::vector<std::string>,
Wondering why the following is valid:
if ( vecMetaData[0] != "Some string" )
{
...
But not this:
switch ( vecMetaData[1] )
{
...
Visual studio complains :
error C2450: switch expression of type 'std::basic_string<_Elem,_Traits,_Ax>' is illegal
1> with... | switch() needs an integral type (like int, char, ...)
string is not an integral type, neither does string have an implicit conversion to an integral type, so it can't be used in a switch statement
|
309,491 | 309,523 | How do I read the results of a system() call in C++? | I'm using the following code to try to read the results of a df command in Linux using popen.
#include <iostream> // file and std I/O functions
int main(int argc, char** argv) {
FILE* fp;
char * buffer;
long bufSize;
size_t ret_code;
fp = popen("df", "r");
if(fp == NULL) { // head off errors r... | Why would std::malloc() fail?
The obvious reason is "because std::ftell() returned a negative signed number, which was then treated as a huge unsigned number".
According to the documentation, std::ftell() returns -1 on failure. One obvious reason it would fail is that you cannot seek in a pipe or FIFO.
There is no esca... |
309,581 | 309,589 | What is the difference between const_iterator and non-const iterator in the C++ STL? | What is the difference between a const_iterator and an iterator and where would you use one over the other?
| const_iterators don't allow you to change the values that they point to, regular iterators do.
As with all things in C++, always prefer const, unless there's a good reason to use regular iterators (i.e. you want to use the fact that they're not const to change the pointed-to value).
|
309,672 | 586,954 | Can I use boost on uclibc linux? | Does anyone have any experience with running C++ applications that use the boost libraries on uclibc-based systems? Is it even possible? Which C++ standard library would you use? Is uclibc++ usable with boost?
| We use Boost together with GCC 2.95.3, libstdc++ and STLport on an ARMv4 platform running uClinux. Some parts of Boost are not compatible with GCC 2.x but the ones that are works well in our particular case. The libraries that we use the most are date_time, bind, function, tuple and thread.
Some of the libraries we had... |
310,031 | 310,053 | Open a Specified File in Excel from a GUI - Borland C++ | I am using Borland Builder C++ 2009. I want to add a button to a form that allows the user to open a file in Excel that I specify. I can't think of how to do this. I know how to link with other code and executables -- is there a Microsoft Excel executable that I could use? How could I specify the file then? Any hints o... | Assuming that the file type is registered with Excel, you could call ShellExecute() on the file, using the "open" verb. This will cause the file to be opened as if double clicked by the user in Explorer and will invoke Excel.
If that isn't the case, and you can assume that Excel is installed, you could instead pass "ex... |
310,108 | 310,166 | Can I make GCC warn on passing too-wide types to functions? | Following is some obviously-defective code for which I think the compiler should emit a diagnostic. But neither gcc nor g++ does, even with all the warnings options I could think of: -pedantic -Wall -Wextra
#include <stdio.h>
short f(short x)
{
return x;
}
int main()
{
long x = 0x10000007; /* bigger than s... | Use -Wconversion -- the problem is an implicit cast (conversion) from long x to short when the function f(short x) is called [not printf], and -Wconversion will say something like "cast from long to short may alter value".
..
Edit: just saw your note. -Wconversion results in a warning for me, using g++ 4.3.2 on Linux.... |
310,175 | 311,698 | What is the widget name of the Kde bar used in program like Kate? (image inside) | What is the object name of the Kde bar that provide buttons to hide/unhide widgets? I can't find on kde official API references. It's used in program like Kate, Kdevelop. Here the screenshot of the bar of Kate bottom:
http://emilio.plugs.it/bar.png
alt text http://emilio.plugs.it/bar.png
| Isn't that a KMultiTabBar?
|
310,192 | 310,195 | Visual Studio C++ project management. How do I handle non-code files in a project? | I have a project in a c++ solution. For that project, I have some config files that I would like to manage from within the project and when I build the project, have those config files added to the executable build path in the proper directory structure.
Example:
test.exe references config/myconfig.txt
Is there a way t... | You could use pre-build events to create the directories and copy the files.
|
310,333 | 310,364 | tr1::mem_fn and tr1::bind: on const-correctness and overloading | What's wrong with the following snippet ?
#include <tr1/functional>
#include <functional>
#include <iostream>
using namespace std::tr1::placeholders;
struct abc
{
typedef void result_type;
void hello(int)
{ std::cout << __PRETTY_FUNCTION__ << std::endl; }
void hello(int) const
{ std::cout << __P... | The lookup is done at a time when the constness of this is not known. You just have to give it a hint via casting. Try this:
typedef void (abc::*fptr)(int) const; // or remove const
std::tr1::bind((fptr)&abc::hello, x , _1)(a);
You may also notice here that removing the const still works. This is because you should... |
310,358 | 310,455 | Quick file access in a directory with 500,000 files | I have a directory with 500,000 files in it. I would like to access them as quickly as possible. The algorithm requires me to repeatedly open and close them (can't have 500,000 file open simultaneously).
How can I do that efficiently? I had originally thought that I could cache the inodes and open the files that way, ... | Assuming your file system is ext3, your directory is indexed with a hashed B-Tree if dir_index is enabled. That's going to give you as much a boost as anything you could code into your app.
If the directory is indexed, your file naming scheme shouldn't matter.
http://lonesysadmin.net/2007/08/17/use-dir_index-for-your-n... |
310,363 | 310,374 | How to add one day to a time obtained from time() | I have a time represented as the number of seconds elapsed since midnight, January 1, 1970, UTC (the results of an earlier call to time()). How do I add one day to this time?
Adding 24 * 60 * 60 works in most cases, but fails if the daylight saving time comes on or off in between. In other words, I mostly want to add 2... | use gmtime() to convert the time_t to a struct tm
add one to the day (tm_mday)
use mktime() to convert the struct tm back to a time_t
see time.h for more info
Edit:
I just tried it, this works:
int main()
{
time_t base = 1142085600;
for(int i = 0; i < 4; ++i) {
struct tm* tm = localtime(&base);
tm->tm_mday ... |
310,392 | 310,404 | Char ^= 0xB3 equivalent in VBScript | I have the following C++ code:
Char ^= 0xB3;
Char is a single character in a string. Is there an equivalent in VBScript?
| Char = chr(asc(Char) xor &HB3)
|
310,408 | 310,499 | Deriving an abstract class from concrete class | Let's say we have a concrete class Apple. (Apple objects can be instantiated.)
Now, someone comes and derives an abstract class Peach from Apple. It's abstract because it introduces a new pure virtual function. The user of Peach is now forced to derive from it and define this new function. Is this a common pattern? Is ... | Re Peach from Apple:
Don't do it if Apple is a value class
(i.e. has copy ctor, non-identical
instances can be equal, etc). See Meyers
More Effective C++ Item 33 for why.
Don't do it if Apple has a public
nonvirtual destructor, otherwise you
invite undefined behaviour when your
users delete an Apple through a
pointe... |
310,557 | 310,566 | C++ Nested classes forward declaration error | I am trying to declare and use a class B inside of a class A
and define B outside A.
I know for a fact that this is possible because Bjarne Stroustrup
uses this in his book "The C++ programming language"
(page 293,for example the String and Srep classes).
So this is my minimal piece of code that causes problems
class A... | Define the constructor for A AFTER the definition of struct B.
|
311,102 | 324,739 | Safely checking the type of a variable | For a system I need to convert a pointer to a long then the long back to the pointer type. As you can guess this is very unsafe. What I wanted to do is use dynamic_cast to do the conversion so if I mixed them I'll get a null pointer. This page says http://publib.boulder.ibm.com/infocenter/lnxpcomp/v7v91/index.jsp?topic... | I've had to do similar things when loading C++ DLLs in apps written in languages that only support a C interface. Here is a solution that will give you an immediate error if an unexpected object type was passed in. This can make things much easier to diagnose when something goes wrong.
The trick is that every class th... |
311,166 | 311,252 | std::auto_ptr or boost::shared_ptr for pImpl idiom? | When using the pImpl idiom is it preferable to use a boost:shared_ptr instead of a std::auto_ptr? I'm sure I once read that the boost version is more exception friendly?
class Foo
{
public:
Foo();
private:
struct impl;
std::auto_ptr<impl> impl_;
};
class Foo
{
public:
Foo();
private:
struct impl;
... | You shouldn't really use std::auto_ptr for this. The destructor won't be visible at the point you declare the std::auto_ptr, so it might not be called properly. This is assuming that you are forward declaring your pImpl class, and creating the instance inside the constructor in another file.
If you use boost::scoped_pt... |
311,247 | 311,556 | Changing default behavior in a C++ application with plugins | In short: what is the best way to design and implement a factory+plugin mechanism, so that plugins can replace objects in the main application.
We have a code base from which we build our applications. The code base is fine for 70-95% of the applications, meaning that in each new application we need to change 5-30% of ... | There was an article a while back in Doctor Dobb's that discussed this exact problem. Here is a link to the article in question.
As an aside you may want to stick with a straight C interface for the plugins to your project. That way you can link code written in almost any language into your framework with minimal hassl... |
311,297 | 311,606 | Fast container for setting bits in a sparse domain, and iterating (C++)? | I need a fast container with only two operations. Inserting keys on from a very sparse domain (all 32bit integers, and approx. 100 are set at a given time), and iterating over the inserted keys. It should deal with a lot of insertions which hit the same entries (like, 500k, but only 100 different ones).
Currently, I'm ... | Depending on the distribution of the input, you might be able to get some improvement without changing the structure.
If you tend to get a lot of runs of a single value, then you can probably speed up insertions by keeping a record of the last value you inserted, and don't bother doing the insertion if it matches. It c... |
311,735 | 311,764 | check if X is derived of Y via typeid | i need to convert pointers to long (SendMessage())
and i want to safely check if the variable is correct on the otherside. So i was thinking of doing dynamic_cast but that wont work on classes that are not virtual. Then i thought of doing typeid but that will work until i pass a derived var as its base.
Is there any wa... | If all you have is a long, then there's not really much you can do. There is no general way to determine whether an arbitrary number represents a valid memory address. And even if you know it's a valid memory address, there is no way to determine the type of the thing the pointer points to. If you can't be sure of the ... |
311,805 | 311,974 | Access desktop release directory from windows ce device | I am writing a test program to copy some file in Application data folder on device to release directory on desktop.
I am not sure how to access release dir on desktop?
Is there any shell command to do that?
Basically I want to write c++ program that will run on device to accomplish this task.
| I found the solution
There is API called CoyFile that can copy to release dir.
CopyFile(Src file,Dest file,FALSE);
Destination file can be given as
ce::wstring = L"\release\foo.txt";
|
311,949 | 312,042 | Unit testing destructors? | Is there any good way to unit test destructors? Like say I have a class like this (contrived) example:
class X
{
private:
int *x;
public:
X()
{
x = new int;
}
~X()
{
delete x;
}
int *getX() {return x;}
const int *getX() const {return x;}
};
Is there any good wa... | There may be something to be said for dependency injection. Instead of creating an object (in this case an int, but in a non-contrived case more likely a user-defined type) in its constructor, the object is passed as a parameter to the constructor. If the object is created later, then a factory is passed to the constru... |
312,077 | 312,078 | Dot product in C++ using generic algorithms | I´m sure there´s a clever one-liner using the C++ stl generic algorithms for implementing the dot product of the elements in any ordered container, such as a vector or list. I just don´t seem to remember it!
The fancy implementation would be:
template <class containerT>
typename containerT::value_type dot_product (cons... | See std::inner_product from <numeric>.
|
312,115 | 312,402 | C++ Linking Errors: Undefined symbols using a templated class | I'm getting some really wierd linking errors from a class I wrote. I am completely unable to find anything that will describe what is happening.
Visual Studio (Windows XP)
players.obj : error LNK2019: unresolved external symbol "public: __thiscall TreeNode::TreeNode(void)" (??0?$TreeNode@VPlayer@@@@QAE@XZ) referenced... | When you define your template in a .cpp file, you have to explicitly instantiate it with all the types / template parameters known the template will be used beforehand like this (put it in the .cpp file):
template class TreeNode<Player>;
If you don't know with which template parameters the template will be used, you h... |
312,116 | 312,125 | C++ array size dependent on function parameter causes compile errors | I have a simple function in which an array is declared with size
depending on the parameter which is int.
void f(int n){
char a[n];
};
int main() {
return 0;
}
This piece of code compiles fine on GNU C++, but not on MSVC 2005.
I get the following compilation errors:
.\main.cpp(4) :... | What you have found it one of the Gnu compiler's extensions to the C++ language. In this case, Visual C++ is completely correct. Arrays in C++ must be defined with a size that is a compile-time constant expression.
There was a feature added to C in the 1999 update to that language called variable length arrays, where... |
312,286 | 312,288 | Returning a pointer from a class | For my programming class I have to write a linked list class. One of the functions we have to include is next(). This function would return the memory address of the next element in the list.
#include <iostream>
using namespace std;
class Set {
private:
int num;
Set *nextval;
bool empty;
... | Set* is correct. You are suffering from a rather silly bug in this function:
Set* Set::next() {
Set *current;
current = this;
return current->next;
}
The last line should be return current->nextval. Otherwise you are trying to return a pointer to the next function... probably not what you want, ever. :-... |
312,312 | 312,352 | What are some reasons a Release build would run differently than a Debug build | I have a Visual Studio 2005 C++ program that runs differently in Release mode than it does in Debug mode. In release mode, there's an (apparent) intermittent crash occurring. In debug mode, it doesn't crash. What are some reasons that a Release build would work differently than a Debug build?
It's also worth mention... | Surviving the Release Version gives a good overview.
Things I have encountered - most are already mentioned
Variable initialization
by far the most common. In Visual Studio, debug builds explicitly initialize allocated memory to given values, see e.g. Memory Values here. These values are usually easy to spot, cause an... |
312,570 | 312,613 | What are some of the drawbacks to using C-style strings? | I know that buffer overruns are one potential hazard to using C-style strings (char arrays). If I know my data will fit in my buffer, is it okay to use them anyway? Are there other drawbacks inherent to C-style strings that I need to be aware of?
EDIT: Here's an example close to what I'm working on:
char buffer[1024]... | C strings lack the following aspects of their C++ counterparts:
Automatic memory management: you have to allocate and free their memory manually.
Extra capacity for concatenation efficiency: C++ strings often have a capacity greater than their size. This allows increasing the size without many reallocations.
No embedd... |
312,749 | 312,766 | Providing an iterator for the first element of a container of pairs | I have a container filled with pairs. I want to iterate in it using the STL generic algorithms (in my case it would be inner_product, but consider it as a generic problem).
The algorithm I am using expects iterators first and last. Can I provide special iterators first and last that will iterate not on the pairs but on... | I've looked around and found boost::transform_iterator. I've come up with this code. Surprising how well it works:
#include <map>
#include <algorithm>
#include <iostream>
#include <string>
#include <iterator>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
int m... |
312,895 | 312,908 | What are signals and slots? | Can someone explain in simple terms the "signals and slots" pattern?
| Signals and slots are a way of decoupling a sender (the signal) and zero or more receivers (the slots). Let's say you a system which has events that you want to make available to any other part of the system interested in those events. Rather than hard-wiring the code that generates event to the code that wants to know... |
312,957 | 312,959 | How would I use the >> and << operators for binary data in C++? | Is there a way to use these operators to input and output binary data? The reason I want to do this is that it makes the code readable.
Ex: infile >> filedecrypter >> metadataparser >> audiodecoder >> effects >> soundplayer;
| Indeed that can be done, if the library or your code provides the overloads for operator<< and operator>> for it to work. Simple example on how one could do it:
class transformer {
public:
virtual std::iostream& transform(std::iostream&) = 0;
};
class noise : public transformer {
public:
virtual std::i... |
313,141 | 313,144 | static_cast confusion caused by inconsistencies | Why whenever I compile and run the following code in Visual Studio 2008:
double value1 = 10.5;
double value2 = 15.5;
int whole_number = value1 + value2;
Console::WriteLine(whole_number);
I get an incorrect value of 26 while the answer is 25.
However when I use static casts on the doubles, I get the right answer which ... | It's absolutely right.
double value1 = 10.5;
double value2 = 15.5;
int whole_number = value1 + value2; // int whole_number = 26.0;
Console::WriteLine(whole_number);
What would you expect instead? The compiler first evaluates the right side, and then implicitly converts to the int. Thus, 26.0 becomes 26
When you cast b... |
313,432 | 313,444 | C++ extend a vector with another vector | I'm a C/Python programmer in C++ land working with the STL for the first time.
In Python, extending a list with another list uses the .extend method:
>>> v = [1, 2, 3]
>>> v_prime = [4, 5, 6]
>>> v.extend(v_prime)
>>> print(v)
[1, 2, 3, 4, 5, 6]
I currently use this algorithmic approach to extend vectors in C++:
v.res... | From here
// reserve() is optional - just to improve performance
v.reserve(v.size() + distance(v_prime.begin(),v_prime.end()));
v.insert(v.end(),v_prime.begin(),v_prime.end());
|
313,446 | 313,488 | Can anyone quantify performance differences between C++ and Java? | Java was initially slow before the JIT but today performance is pretty close to C++. I want to know if someone has done measurable performance comparisons between the two languages? Where does Java fall short when compared to C++? Java provides many productivity gains to developers so they can write applications muc... | JIT compilers can be faster for many individual code constructs because they can take advantage of runtime profiling of code.
For example, VonC in his answer to this question mentions heap allocation for all objects. This is not actually true: the JIT can allocate objects on the stack if it can prove by escape analysis... |
313,712 | 313,717 | What is the best method to ping in c++ under linux? | I have to call ping from c++ code.I'd like to easily read the output for further utilizations.
I have come up with two solutions:
use a fork and a pipe, redirect ping output to the pipe and then parse it
find a library suited for the purpose to use a ping(ip_addresss) function directly
I'd like the latter but i didn'... | I would go with your first option. Linux is built around the concept of having small, specialized apps which do one thing really well, communicating with pipes. Your app shouldn't include a library to implement ping, since there is already a built-in command to do it, and it works very well!
|
313,753 | 313,776 | Char array to a class | I have a incoming stream of bytes (unsigned char) from either a file or network. I need this data placed in a class, and is looking for a NET-way of doing this.
I bet some does this all the time, so I guess there is a better method to do this than using BitConverter.
I realize I supplied too litle information. Let me... | As Jon mentioned, it's not clear, what you need. Maybe you are talking about maybe it is Binary serialization what you are looking for?
|
313,778 | 313,787 | generate dependencies for a makefile for a project in C/C++ | I have a project that has a makefile with broken dependencies. Is there any best known way to generate a list of dependencies for the project that I can use in the makefile, other than examining each source file by hand or with a hand written perl script?
| GNU make's documentation provides a good solution.
Absolutely. g++ -MM <your file> will generate a GMake compatible list of dependencies. I use something like this:
# Add .d to Make's recognized suffixes.
SUFFIXES += .d
#We don't need to clean up when we're making these targets
NODEPS:=clean tags svn
#Find all the C++... |
313,882 | 313,883 | Can you invoke an instantiated object's class constructor explicity in C++? | After creating a instance of a class, can we invoke the constructor explicitly?
For example
class A{
A(int a)
{
}
}
A instance;
instance.A(2);
Can we do this?
| You can use placement new, which permits
new (&instance) A(2);
However, from your example you'd be calling a constructor on an object twice which is very bad practice. Instead I'd recommend you just do
A instance(2);
Placement new is usually only used when you need to pre-allocate the memory (e.g. in a custom memory ... |
313,970 | 313,990 | How to convert an instance of std::string to lower case | I want to convert a std::string to lowercase. I am aware of the function tolower(). However, in the past I have had issues with this function and it is hardly ideal anyway as using it with a std::string would require iterating over each character.
Is there an alternative which works 100% of the time?
| Adapted from Not So Frequently Asked Questions:
#include <algorithm>
#include <cctype>
#include <string>
std::string data = "Abc";
std::transform(data.begin(), data.end(), data.begin(),
[](unsigned char c){ return std::tolower(c); });
You're really not going to get away without iterating through each character. T... |
314,012 | 314,018 | Returning an Iterator | I have a function which searches an STL container then returns the iterator when it finds the position, however I am getting some funny error messages, can tell me what I am doing wrong?
Function:
std::vector< CClass >::iterator CClass::SearchFunction( const std::string& strField )
{
...
return it;
...
}
Error:
e... | Your search function is returning a const_iterator. You should either return the same type, i.e. std::vector< CClass >::const_iterator, or cast it to a std::vector< CClass >::iterator if you intend the caller to be able to modify the found item through the iterator.
EDIT: after seeing your update, it seems the problem ... |
314,152 | 314,180 | How to declare/define a class with template template parameters without using an extra template parameter | Consider the following use of template template parameters...
#include <iostream>
template <typename X>
class A
{
X _t;
public:
A(X t)
:_t(t)
{
}
X GetValue()
{
return _t;
}
};
template <typename T, template <typename T> class C >
class B
{
C<T> _c;
public:
B(T t)
... | I assume you're after X, as well as A, in your code.
The usual pattern is to have
template<typename C>
struct B
{
C c;
};
and then, inside classes eligible for substitution:
template<typename X>
class A
{
typedef X type_name;
X t;
};
Then you can access the template parameter using C::type_name.
|
314,176 | 314,354 | Image processing: smart solution for converting superixel (128x128 pixel) coordinates needed | A cancer CT picture is stored inside a unsigned short array (1-dimensional).
I have the location information of the cancer region inside the picture, but the coordinates (x,y) are in superpixel (128x128 unsigned short). My task is to highlight this region.
I already solved this one by converting superpixel coordinate... | From what I understand you have:
A large image that is a CT scan
A rectangular area within that image that is a cancer
Then it gets a bit harder to understand. I believe you want to create some sort of class so that you can effectively access 128x128 blocks of the image as if they were a single pixel.
So if the image... |
314,492 | 314,527 | Is there an easy way to sort an array of char*'s ? C++ | I've got an array of char* in a file.
The company I work for stores data in flat files.. Sometimes the data is sorted, but sometimes it's not.
I'd like to sort the data in the files.
Now I could write the code to do this, from scratch.
Is there an easier way?
Of course an in-place sort would be the best option. I'm... | template<size_t length> int less(const char* left, const char* right) {
return memcmp(left, right, length) < 0;
}
std::sort(array, array + array_length, less<buffer_length>);
|
314,531 | 314,894 | Windows GDI: horizontal/vertical DPI | When obtaining the DPI for the screen under Windows (by using ::GetDeviceCaps) will the horizontal value always be the same as the vertical? For example:
HDC dc = ::GetDC(NULL);
const int xDPI = ::GetDeviceCaps(dc, LOGPIXELSX);
const int yDPI - ::GetDeviceCaps(dc, LOGPIXELSY);
assert(xDPI == yDPI);
::ReleaseDC(NULL, d... | It's possible for it to be different, but that generally only applies to printers. It can be safely assumed that the screen will always have identical horizontal and vertical DPIs.
|
314,553 | 314,601 | How to use makefiles in Visual Studio? | I heard a lot about makefiles and how they simplify the compilation process. I'm using VS2008. Can somebody please suggest some online references or books where I can find out more about how to deal with them?
| A UNIX guy probably told you that. :)
You can use makefiles in VS, but when you do it bypasses all the built-in functionality in MSVC's IDE. Makefiles are basically the reinterpret_cast of the builder. IMO the simplest thing is just to use Solutions.
|
314,584 | 314,613 | Do you declare your module specific functions as static? | I am thinking it is a best practice to declare them as static, as it makes them invisible outside of the module.
What are your thoughts on this?
| If it is truly an function which is internal only to that .c file, then yes. It should help avoid polluting the global namespace. Also, I think that the compiler is able to do some optimizations with calling conventions if the function is static since it knowns no other source file needs to know how to call it. This on... |
314,931 | 314,961 | glibc's '-lmcheck' option and multithreading | We've been trying to hunt down some heap corruption issues in our multi-threaded C++ apps. As one technique, we tried add -lmcheck to the libraries line of the application. This is causing the app to crash out with apparent heap corruption in relatively short order.
Our app does use both malloc/free and new/delete (as ... | No, mcheck is not thread-safe and should not be used with multi-threaded applications. Doing so can introduce additional problems since there is no synchronization between the threads. Here is the response from Ulrich Drepper (glibc maintainer) on the subject a few months ago:
mcheck does not work for multi-threaded... |
314,983 | 315,022 | #include header guard format? | I know it makes little difference to a project but, assuming you use #defined header guards for your C++ code, what format do you use? e.g. assuming a header called foo.hpp:
#ifndef __FOO_HPP__
...
#ifndef INCLUDED_FOO_HPP
...
#ifndef SOME_OTHER_FORMAT
I'm sold on the idea of upper-case #defines but cannot settle o... | I always included the namespace or relative path in the include guard, because only the header name alone has proven to be dangerous.
For example, you have some large project with the two files somewhere in your code
/myproject/module1/misc.h
/myproject/module2/misc.h
So if you use a consistent naming schema for your ... |
315,051 | 315,064 | using a class defined in a c++ dll in c# code | I have a dll that was written in c++, I need to use this dll in my c# code. After searching I found that using P/Invoke would give me access to the function I need, but these functions are defined with in a class and use non-static private member variables. So I need to be able to create an instance of this class to pr... | There is no way to directly use a C++ class in C# code. You can use PInvoke in an indirect fashion to access your type.
The basic pattern is that for every member function in class Foo, create an associated non-member function which calls into the member function.
class Foo {
public:
int Bar();
};
extern "C" Foo... |
315,111 | 315,121 | Cross-platform (linux/Win32) nonblocking C++ IO on stdin/stdout/stderr | I'm trying to find the best solution for nonblocking IO via stdin/stdout with the following characteristics:
As long as there is enough data, read in n-sized chunks.
If there's not enough data, read in a partial chunk.
If there is no data available, block until there is some (even though it may be smaller than n).
Th... | Maybe boost::asio can be of use for you?
|
315,218 | 315,278 | C++ templates and inheritance | My C++ framework has Buttons. A Button derives from Control. So a function accepting a Control can take a Button as its argument. So far so good.
I also have List<T>. However, List<Button> doesn't derive from List<Control>, which means a function accepting a list of Controls can't take a list of Buttons as its argument... | I hate to tell you but if you're using a list of instances to Control instead of pointers to Control, your buttons will be garbage anyway (Google "object slicing"). If they're lists of pointers, then either make the list<button*> into list<control*> as others have suggested, or do a copy to a new list<control*> from t... |
315,261 | 4,498,486 | Using QMDIArea with Qt 4.4. | I'm using the QMdiArea in Qt 4.4.
If a new project is created, I add a number of sub windows to a QMdiArea. I'd like to disallow the user to close a sub window during runtime. The sub windows should only be closed if the whole application is closed or if a new project is created.
How can I do this?
| You need to define your own subWindow. create a subclass of QMdiSubWindow and override the closeEvent(QCloseEvent *closeEvent). you can control it by argument. for example:
void ChildWindow::closeEvent(QCloseEvent *closeEvent)
{
if(/*condition C*/)
closeEvent->accept();
else
closeEvent->ignore(); // you can ... |
315,285 | 315,392 | Can I use two incompatible versions of the same DLL in the same process? | I'm using two commercial libraries that are produced by the same vendor, called VendorLibA and VendorLibB. The libraries are distributed as many DLLs that depend on the compiler version (e.g. VC7, VC8). Both libraries depend on a another library, produced by this vendor, called VendorLibUtils and contained in one DLL.
... | As you are not using VendorLibUtils directly, I assume you can't use LoadLibrary etc.
If the VendorLibUtils DLLs only have exports by ordinal, you could probably rename one of the the libraries and patch the corresponding VendorLibX to use a different filename for its imports.
If the VendorLibUtils DLLs have one or mor... |
315,378 | 315,399 | C++ performance tips and rules of thumb anyone? | When coding, what is a good rule of thumb to keep in mind with respect to performance? There are endless ways to optimize for a specific platform and compiler, but I'm looking for answers that apply equally well (or almost) across compilers and platforms.
| A famous quote come to mind:
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." (Knuth, Donald. Structured Programming with go to Statements, ACM Journal Computing Surveys, Vol 6, No. 4, Dec. 1974. p.268.)
But maybe you should not pass large data stru... |
315,393 | 320,769 | I can't connect KAction to slot on KMainWindow | I have a KMainWindow:
//file.h
class MainWindow: public KMainWindow {
public:
MainWindow(QWidget *parent = 0);
...
...
...
private slots:
void removeClick();
//file.cpp
MainWindow::MainWindow(QWidget *parent) :
KMainWindow(parent) {}
void MainWindow::removeClick()
{
std::cout << "Remove" << std::end... | You forgot the Q_OBJECT macro.
class MainWindow: public KMainWindow
{
Q_OBJECT
public:
// [snip]
}
|
315,437 | 3,131,331 | Detect file handle leaks with Win32 C++ | Is there some way to detect file handle leaks at program termination?
In particular I would like to make sure that all of my handles that get created are being freed in code.
For example, I may have a CreateFile() somewhere, and at program termination I want to detect and ensure that all of them are closed.
| I have used !htrace command of windbg.
!htrace -enable
!htrace -snapshot
!htrace -diff
Allow you to compare the handle situation of two execution point and help you the locate the point where the leaked handle have been allocated.
It worked well for me.
|
315,743 | 617,362 | Detecting loss of connection to fix gateway? (QuickFix) | I'm trying to find a good way to detect a loss of connection.
My adapter is implemented as a Fix::Application based on one of the examples. It uses a socket initiator to connect to the fix gateway.
When I unplug the internet it takes about 30 seconds for the Fix::Application's onLogout method to be fired. It seems li... | The best way to solve this would probably be to decrease your Heartbeat Interval so you know sooner. I don't know of any messages that fire for a loss of TCP connection, but I don't think QuickFix is listening for OS events either. Although, it would likely flow through the fromAdmin event if there were such a message.... |
315,987 | 316,038 | In C++, what do you do nearly all the time? | There are a few things that I almost always do when I put a class together in C++.
1) Virtual Destructor
2) Copy constructor and assignment operator (I either implement them in terms of a private function called Copy(), or declare them private and thus explicitly disallow the compiler to auto generate them).
What thing... | I find turning on the gcc flags -Wall, -Werror, and (this is the fun one) -Weffc++ help catch a lot of potential problems. From the gcc man page:
-Weffc++ (C++ only)
Warn about violations of the following style guidelines from Scott
Meyers’ Effective C++ book:
· Item 11: Define a copy construct... |
316,181 | 316,202 | Why does the compiler choose bool over string for implicit typecast of L""? | Having recently introduced an overload of a method the application started to fail.
Finally tracking it down, the new method is being called where I did not expect it to be.
We had
setValue( const std::wstring& name, const std::wstring& value );
std::wstring avalue( func() );
setValue( L"string", avalue );
std::wstrin... | First, the cause of this issue: C++ Standard [over.ics.rank]/2.11 defines an order for conversion sequences. It says that a user defined conversion sequence is worse than a standard conversion sequence. What happens in your case is that the string literal undergoes a boolean-conversion (defined at 4.12. This is a stand... |
316,200 | 316,245 | Which C++ Library for CGI Programming? | I'm looking at doing some work (for fun) in a compiled language to run some simple tests and benchmarks against php.
Basically I'd like to see what other people use for C++ CGI programming. (Including backend database, like mysql++ or something else)
| I'm not sure exactly what you're looking for, but there is a C++ web framework called wt (pronounced "witty"). It's been kept pretty much up to date and if you want robust C++ server-side code, this is probably what you're looking for.
You can check it out and read more at the wt homepage.
P.S. You may have some troubl... |
316,400 | 317,237 | Profiling Qt application that uses plugins | I have a medium sized application written in c++ using Qt. I wanted to profile things to see where my least performant code was so I compiled everything with -pg.
However, my application makes use of a lot of plugins using the QTPlugin mechanism (boils down to a dlopen and a dlsym of a instance object per plugin). I've... | If you can use it, I think Valgrind's callgrind only needs debug symbols (-g) to profile code. I'm not sure if it works with dynamically linked objects, though.
|
316,436 | 316,451 | What tools do you use to profile (native)C++ on Windows? | How do Window's programmers profile their native C++ code?
On Unix/Linux you have gprof [thanks Evan] & valgrind (I personally used this one, although it's not a real profiler), and recently I'm on Mac and Solaris, which means I moved to dTrace. Now when I've had the need to profile on Windows in the past, like at my p... | You should give Xperf a try - it's a new system wide performance tool that can drill down to a particular application and what exactly it's doing inside itself as well as what's it's asking of the OS.
It's freely available on the Windows SDK for Windows Server 2008 and .NET Framework 3.5 ISO:
Install the SDK by downl... |
316,626 | 1,174,697 | How do I read from a version resource in Visual C++ | I have a version resource in my resources in a C++ project which contains version number, copyright and build details. Is there an easy way to access this at run-time to populate my help/about dialog as I am currently maintaining seperate const values of this information. Ideally, the solution should work for Windows... | This is an edited version of my original answer.
bool GetProductAndVersion(CStringA & strProductName, CStringA & strProductVersion)
{
// get the filename of the executable containing the version resource
TCHAR szFilename[MAX_PATH + 1] = {0};
if (GetModuleFileName(NULL, szFilename, MAX_PATH) == 0)
{
... |
317,087 | 317,100 | boost lambda for_each / transform puzzle | Does anybody know why
vector<int> test(10);
int a=0;
for_each(test.begin(),test.end(),(_1+=var(a),++var(a)));
for_each(test.begin(),test.end(),(cout << _1 << " "));
cout << "\n"
Gives : "0 1 2 3 4 5 6 7 8 9"
but
transform(test.begin(),test.end(),test.begin(), (_1+=var(a),++var(a)));
...(as before)
G... | Comma operator evaluates left to right, so the result of the
_1+=var(a), ++var(a)
is ++var(a), which you'll store using the transform version.
for_each:
_1 += var(a) is evaluated, updating your sequence (via the lambda _1), then ++var(a) is evaluated, but this has no effect on your sequence.
transform:
_1+=var(a) is... |
317,140 | 317,145 | Get dimensions of JPEG in C++ | I need to get the image dimensions of a JPEG in C++. I'm looking for either a fairly simple way to do it or a smallish library that provides that functionality. I'm working in C++ on OpenVMS, so any external libraries may have to be adapted to compile on our systems - so please don't post me links to big, closed source... | You have this C function which may extract the relevant data for you.
This is a C routine but should compile fine with C++.
Pass it a normal FILE pointer (from fopen) to the beginning of a jpeg file and two int pointers to be set with the image height and width.
Or you may find in the Boost library a jpeg class wh... |
317,450 | 317,528 | Why override operator()? | In the Boost Signals library, they are overloading the () operator.
Is this a convention in C++? For callbacks, etc.?
I have seen this in code of a co-worker (who happens to be a big Boost fan). Of all the Boost goodness out there, this has only led to confusion for me.
Any insight as to the reason for this overload?
| One of the primary goal when overloading operator() is to create a functor. A functor acts just like a function, but it has the advantages that it is stateful, meaning it can keep data reflecting its state between calls.
Here is a simple functor example :
struct Accumulator
{
int counter = 0;
int operator()(int... |
317,719 | 317,730 | C++ Namespace question | I am working on some code written by a co-worker who no longer works with the company, and I have found the following code: (which I have cut down below)
namespace NsA { namespace NsB { namespace NsC {
namespace {
class A { /*etc*/ };
class B { /*etc*/ };
}
namespace {
class... | That's an "anonymous namespace" - which creates a hidden namespace name that is guaranteed to be unique per "translation unit" (i.e. per CPP file).
This effectively means that all items inside that namespace are hidden from outside that compilation unit. They can only be used in that same file. See also this article ... |
318,064 | 318,137 | How do you declare an interface in C++? | How do I setup a class that represents an interface? Is this just an abstract base class?
| To expand on the answer by bradtgmurray, you may want to make one exception to the pure virtual method list of your interface by adding a virtual destructor. This allows you to pass pointer ownership to another party without exposing the concrete derived class. The destructor doesn't have to do anything, because the i... |
318,236 | 318,281 | How do you validate that a string is a valid IPv4 address in C++? | I don't need to validate that the IP address is reachable or anything like that. I just want to validate that the string is in dotted-quad (xxx.xxx.xxx.xxx) IPv4 format, where xxx is between 0 and 255.
| You probably want the inet_pton, which returns -1 for invalid AF argument, 0 for invalid address, and +1 for valid IP address. It supports both the IPv4 and future IPv6 addresses. If you still need to write your own IP address handling, remember that a standard 32-bit hex number is a valid IP address. Not all IPv4 addr... |
318,265 | 318,314 | Launching a Process from a Service | I'm trying to launch another process from a service (it's a console app that collects some data and writes it to the registry) but for some reason I can't get it to launch properly.
I basics of what I'm am trying to do is as follows:
Launch the process
Wait for the process to finish
Retrieve the return code from the p... | WaitForSingleObject and GetExitCodeProcess expect the process handle itself, not a pointer to the process handle. Remove the ampersands.
Also, check the return values and call GetLastError when they fail. That will help you diagnose future problems. Never assume an API function will always succeed.
Once you call the fu... |
318,398 | 318,440 | Why does C++ compilation take so long? | Compiling a C++ file takes a very long time when compared to C# and Java. It takes significantly longer to compile a C++ file than it would to run a normal size Python script. I'm currently using VC++ but it's the same with any compiler. Why is this?
The two reasons I could think of were loading header files and runnin... | Several reasons
Header files
Every single compilation unit requires hundreds or even thousands of headers to be (1) loaded and (2) compiled.
Every one of them typically has to be recompiled for every compilation unit,
because the preprocessor ensures that the result of compiling a header might vary between every compil... |
318,420 | 318,502 | ApplicationVerifier is not detecting handle leaks, what do I do? | I did select the executable correctly, because I can get it to respond to certain things I do. But I can't get ApplicationVerifier to properly detect a handle leak.
Here is an example:
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
... | Is your code only creating handles through CreateFile? If so you can just macro these methods out to versions that do custom implemented leak detection. It's a lot of work but it will get the job done.
#if DEBUG
#define CreateFile DebugCreateFile
#define CloseHandle DebugCloseHandle
#endif
// in another cpp file
#und... |
318,511 | 318,520 | Init Structure with std::wstring | I've got a structure as follows:
typedef struct
{
std::wstring DevAgentVersion;
std::wstring SerialNumber;
} DeviceInfo;
But when I try to use it I get all sorts of memory allocation errors.
If I try to pass it into a function like this:
GetDeviceInfo(DeviceInfo *info);
I will get a runtime check error compl... | You should use new instead of malloc, to assure the constructor gets called for the DeviceInfo and its contained wstrings.
DeviceInfo *info = new DeviceInfo;
In general, it's best to avoid using malloc in C++.
Also, make sure to delete the pointer when you're done using it.
Edit: Of course if you only need info in the... |
318,641 | 319,613 | Multiple QMainWindow instances? | The QMainWindow is the main window in a Qt application. So usually you'd have only one, but would it be possible at all to have multiple QMainWindow instances in your application?
I am working on integrating a Qt-based GUI application B into another Qt-based GUI application A. Both these applications have a QMainWindo... | You can have as many QMainWindow instances as you want. A QMainWindow is just a QWidget which provides a menu bar, toolbar, status bar and docking framework. But basically it is just a QWidget so you can have as many as you like.
Normally you only have a single QMainWindow for GUI design reasons since it can be confusi... |
318,835 | 318,881 | Do you add information to the top of each .hpp/.cpp file? | When creating a new C++ header/source file, what information do you add to the top? For example, do you add the date, your name, a description of the file, etc.? Do you use a structured format for this information?
e.g.
// Foo.cpp - Implementation of the Foo class
// Date: 2008-25-11
// Created by: John Smith
One te... | Information about who created a file and when and who edited it and when is all in source control. If your team has good practices around check-in comments, then you'll know the reasons for each change too. No need for comments for that stuff.
I think it's 100% legit - wise, even - to put a comment block, as long as ... |
319,154 | 319,196 | boost::any_cast - throw only when an implicit conversion isn't available? | I want boost::any_cast<T> to only throw an exception when the type of the any doesn't have an implicit conversion to T. The normal behaviour seems to be to throw an exception if the type of the any is not T, regardless of implicit conversions.
Example:
boost::any a = 1;
boost::any_cast<int>(a); // This succeeds, and ri... | Well you can't do it. The any mechanism works like this:
struct base {
virtual ~base() { }
};
template<typename T>
struct concrete_base : base {
T t;
concrete_base(T t):t(t) { }
};
struct my_any {
base * b;
template<typename T>
my_any(T t):b(new concrete_base<T>(t)) { }
template<typename... |
319,171 | 324,903 | What Arguments are you supposed to give to the Windows API call VerQueryValue | I understand the first argument must be the result of GetFileVersionInfo().
The third and forth are target buffer and size
What is the second argument, lpSubBlock?
Thanks In Advance
| When you view the version info through the resource editor you might notice that there is an initial section with FILEVERSION, PRODUCTVERISON etc. and then one or more blocks which contain language specific settings.
VS_VERSION_INFO VERSIONINFO
FILEVERSION 5,0,0,0
PRODUCTVERSION 5,0,0,0
FILEFLAGSMASK 0x3fL
#ifdef _D... |
319,292 | 319,306 | Changing the reserve memory of C++ vector | I have a vector with 1000 "nodes"
if(count + 1 > m_listItems.capacity())
m_listItems.reserve(count + 100);
The problem is I also clear it out when I'm about to refill it.
m_listItems.clear();
The capacity doesn't change.
I've used the resize(1); but that doesn't seem to alter the capacity.
So how does one ch... | vector<Item>(m_listItems).swap(m_listItems);
will shrink m_listItems again: http://www.gotw.ca/gotw/054.htm (Herb Sutter)
If you want to clear it anyway, swap with an empty vector:
vector<Item>().swap(m_listItems);
which of course is way more efficient. (Note that swapping vectors basicially means just swapping two p... |
319,395 | 319,404 | Pointer Pointer Methods C++ | I have two questions:
1) How can I make an array which points to objects of integers?
int* myName[5]; // is this correct?
2) If I want to return a pointer to an array, which points to objects (like (1)) how can I do this in a method? ie) I want to impliment the method:
int **getStuff() {
// what goes here?
return *(m... |
How can I make an array which points
to objects?
int * myName[5]; /* correct */
If I want to return a pointer to an
array, which points to objects (like
(1)) how can I do this in a method?
Technically, you write this function:
int * (* getStuff() )[5] {
return &myName;
}
That returns a pointer to that a... |
319,623 | 319,663 | C++ Parameter Reference | void (int a[]) {
a[5] = 3; // this is wrong?
}
Can I do this so that the array that is passed in is modified?
Sorry for deleting, a bit new here...
I have another question which might answer my question:
If I have
void Test(int a) {
}
void Best(int &a) {
}
are these two statements equivalent?
Test(a);
Best(&a... | void Test(int a[])
{
a[5] = 3;
}
just alternate syntax for:
void Test(int* a)
{
*(a+5) = 3;
}
No array is passed, just a pointer. The original array is modified.
As for your second revision, given:
void Test(int a)
{
}
void Best(int &a)
{
}
then
Test(aa); // Passes aa by value. Changes to a in T... |
319,790 | 319,930 | SQLite C/C++ API unsigned char * | Why does the SQLite C/C++ API return unsigned char *s for text values as opposed to the more de-facto char * type?
This is somewhat related to the unsigned char question, except that the SQLite API's decision seems opposite of the conventional char * advice given for string-like values.
For example:
const unsigned char... | From the SQLite documentation:
(H13821) The sqlite3_column_text(S,N) interface converts the Nth column in the current row of the result set for the prepared statement S into a zero-terminated UTF-8 string and returns a pointer to that string.
UTF-8 wants byte values ranging from 0x00 to 0xFF. char can range from -0x... |
319,880 | 319,901 | Integer division rounding with negatives in C++ | Suppose a and b are both of type int, and b is nonzero. Consider the result of performing a/b in the following cases:
a and b are both nonnegative.
a and b are both negative.
Exactly one of them is negative.
In Case 1 the result is rounded down to the nearest integer. But what does the standard say about Cases 2 an... | According to the May 2008 revision,
You're right:
The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands... |
320,124 | 320,136 | Debugging an application in Linux | I want to debug an application in Linux.
The application is created in C++. The GUI is created using QT.
The GUI is linked with a static library that can be treated as the back end of the application.
I want to debug the static library but am not sure how to do that.
I tried using gdb
gdb GUI
But how can I attach the ... | gdb will automatically debug functions in the library when they are called. just call it like
gdb ./foo
run
:) . Be sure you build foo with debugging flags (-g3 will enable all debugging stuffs for gcc :). You should not optimize when debugging (pass at most -O1 to gcc, do not optimize further). It can confuse the deb... |
320,506 | 320,515 | C++: how to create an array of objects on the stack? | Consider the following piece of Java code.
int N = 10;
Object obj[] = new Object[N];
for (int i = 0; i < N; i++) {
int capacity = 1000 * i;
obj[i] = new ArrayList(capacity);
}
Because in Java, all objects live on the Heap, the array does not
contain the objects themselves, but references to the objects. Also,
... | For an array of ArrayList objects:
ArrayList obj[10];
The objects will be default initialised, which is fine for user-defined types, but may not be what you want for builtin-types.
Consider also:
std::vector<ArrayList> obj(10, ArrayList());
This initialises the objects by copying whatever you pass as the second param... |
320,600 | 320,701 | How to automatically create a file with the latest compile time and include it into a library? | I have a library consisting of approx 100 source files. I want one of the sources to be always rebuilt if any of the other files have been compiled but I don't want it built every time I run the make/build.
Basically I want this file to have the last build date/time built into it so any application linking to the libra... | To expand slightly on JesperE's solution.
Let the object file depend on all targets which the executable depends on, (excluding itself).
So if all the executable depends on is objects, then JesperE is completely correct.
Otherwise, you could rebuild the executable without updating the timestamp, in the case where one o... |
320,618 | 320,627 | How to resolve name collision when using c headers? | I am currently doing some socket programming using C/C++. To be able to use a somewhat cleaner interface, and a more OO structure, I decided to write a few simple wrapper classes around parts of the C socket API, but while doing so I stumbled upon a problem:
Given the following code:
// Global method
int foo(int x)
{
... | The problem is that it first looks in the scope of your class, and finds a foo function. The lookup will stop then, and the compiler tries to match arguments. Since it only has the one foo function in that scope in your class, calling the function fails.
You need to explicitly state that you want to call the free funct... |
320,677 | 320,688 | How do I set the icon for my application in visual studio 2008? | How do I set the executable icon for my C++ application in visual studio 2008?
| First go to Resource View (from menu: View --> Other Window --> Resource View). Then in Resource View navigate through resources, if any. If there is already a resource of Icon type, added by Visual Studio, then open and edit it. Otherwise right-click and select Add Resource, and then add a new icon.
Use the embedded i... |
320,723 | 320,745 | Visual C++ 'Force Includes' option | I have just come across a Visual C++ option that allows you to force file(s) to be included - this came about when I was looking at some code that was missing a #include "StdAfx.h" on each .cpp file, but was actually doing so via this option.
The option can be found on the Advanced C/C++ Configuration Properties page a... | I would discourage from /FI (MSDN says it's called /FI . Not sure whether i looked at the right page though), simply because people or yourself reading the files don't notice a header is magically included anyway.
You can be sure this will cause much debugging time for someone that wants to figure out where specific ... |
320,798 | 320,811 | Adding types to the std namespace | Is it acceptable to add types to the std namespace. For example, I want a TCHAR-friendly string, so is the following acceptable?
#include <string>
namespace std
{
typedef basic_string<TCHAR> tstring;
}
Or should I use my own namespace?
| No ... part of the point of a namespace is to prevent name collisions on upgrade.
If you add things to the std namespace, then your code might break with the next release of the library if they decide to add something with the same name.
|
321,068 | 321,080 | Returning multiple values from a C++ function | Is there a preferred way to return multiple values from a C++ function? For example, imagine a function that divides two integers and returns both the quotient and the remainder. One way I commonly see is to use reference parameters:
void divide(int dividend, int divisor, int& quotient, int& remainder);
A variation ... | For returning two values I use a std::pair (usually typedef'd). You should look at boost::tuple (in C++11 and newer, there's std::tuple) for more than two return results.
With introduction of structured binding in C++ 17, returning std::tuple should probably become accepted standard.
|
321,241 | 321,347 | Dead code identification (C++) | I have a large legacy C++ project compiled under Visual Studio 2008. I know there is a reasonably amount of 'dead' code that is not accessed anywhere -- methods that are not called, whole classes that are not used.
I'm looking for a tool that will identify this by static analysis.
This question: Dead code detection in... | You'll want something along the lines of QA-C++ (http://www.programmingresearch.com/QACPP_MAIN.html), also see http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis for similar products.
You're looking for a static code analysis tool that detects unreachable code; many coding guidelines (such as MISRA-C++... |
321,298 | 408,331 | FFMPEG Frame to DirectX Surface | Given a pointer to an AVFrame from FFMPEG's avcodec_decode_video() function how do I copy the image to a DirectX surface? (Assume I have a pointer to an appropriately sized DX X8R8G8B8 surface.)
Thanks.
John.
| You can use FFMPEG's img_convert() function to simultaneously copy the image to your surface and convert it to RGB format. Here's a few lines of code pasted from a recent project of mine which did a similar thing (although I was using SDL instead of DirectX):
AVFrame *frame;
avcodec_decode_video(_ffcontext, fra... |
321,351 | 321,889 | Initializing a union with a non-trivial constructor | I have a structure which I create a custom constructor to initialize the members to 0's. I've seen in older compilers that when in release mode, without doing a memset to 0, the values are not initialized.
I now want to use this structure in a union, but get errors because it has a non-trivial constructor.
So, questio... | Question 1: Default constructors do initialize POD members to 0 according to the C++ standard. See the quoted text below.
Question 2: If a constructor must be specified in a base class, then that class cannot be part of a union.
Finally, you can provide a constructor for your union:
union U
{
A a;
B b;
U() {... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.