Thread: using new with vector<int>*

  1. #1
    Registered User
    Join Date
    May 2005
    Posts
    76

    using new with vector<int>*

    Hello,
    Here is an example of my problem:
    Code:
    #include <vector>
    #include <cstdio>
    
    using namespace std;
    
    int main()
    {
            vector<int> *v;
            int     a;
            scanf("%d", &a);
    
            v=new vector<int>(a);
            if(a<2)
                    return -1;
            v[1]=1;
            return 0;
    }
    When I try to compile it I get such error:
    $ g++ test.cpp
    test.cpp: In function `int main()':
    test.cpp:15: error: no match for 'operator=' in '*(v + 12u) = 1'
    /usr/include/c++/3.4/bits/vector.tcc:131: note: candidates are: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>:perator=(const std::vector<_Tp, _Alloc>&) [with _Tp = int, _Alloc = std::allocator<int>]
    $
    Without line with v[1]=1; it compiles but I don't know what I do wrong. I have ever example of it in Stroustrup's book but I don't know. I just want to have an outcome similar to
    vector<int> v(a);
    but I need v to have global so I have to
    vector<int> *v;
    and then in main() to create it with 'a' amount.
    Can anyone help me?
    Regards.

  2. #2
    Nonconformist Narf's Avatar
    Join Date
    Aug 2005
    Posts
    174
    Your vector isn't a vector, it's a pointer to a vector. You need to dereference the pointer before you can use an overloaded operator:
    Code:
    (*v)[1] = 1;
    Just because I don't care doesn't mean I don't understand.

  3. #3
    Registered User
    Join Date
    May 2005
    Posts
    76
    Ok, I got it. Thank you.

  4. #4
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Also, when you call new, you should also call delete to free the memory (hardly matters here as you're ending the program, and most OS's will not suffer, but it's always worth doing).

    Also checking that new worked is essential (either by catching an exception, or checking for NULL - depending on your compiler and it's complience)

  5. #5
    Nonconformist Narf's Avatar
    Join Date
    Aug 2005
    Posts
    174
    most OS's will not suffer, but it's always worth doing
    Do you know of a remotely common OS that doesn't reclaim a process' memory on termination?
    Also checking that new worked is essential
    Not always. In throwaway code it's easier just to let a bad_alloc exception bomb the program because most of the time the only recovery for an out of memory exception is to terminate. In real world code you have to be more careful, but setting a global exception handler is usually enough to terminate gracefully. That's a lot better than littering your code with try catch statements.
    Just because I don't care doesn't mean I don't understand.

  6. #6
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Quote Originally Posted by Narf
    Do you know of a remotely common OS that doesn't reclaim a process' memory on termination?
    Not personally, I believe Linux does, and I know windows does.

    Not always. In throwaway code it's easier just to let a bad_alloc exception bomb the program because most of the time the only recovery for an out of memory exception is to terminate. In real world code you have to be more careful, but setting a global exception handler is usually enough to terminate gracefully. That's a lot better than littering your code with try catch statements.
    I wouldnt want a released app to bomb where I could help it. Many apps catch heap allocation failures and relay to the user that the app has been unsuccessfull in one of it's procedures - technically, a bad heap allocation can happen regardless of how good your code is; an error message is bad, but a crash is worse IMHO

  7. #7
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> but I need v to have global

    Are you sure about that? You could just create v in main the way Stroustrup does it, and then pass it around to your functions by reference. If you actually mean global (instead of just globally available), then there is no reason to dynamically allocate it, Stroustrup's version would wrok fine as a global object.

    The only time you might need to dynamically allocate something because you need to keep it around for a longer lifetime is if the scope you are creating it in ends before the code that uses it does. Since main() doesn't end until the end of the program, it is unlikely that you would need dynamic memory if you just define the variable in main().
    Last edited by Daved; 09-02-2005 at 12:14 PM.

  8. #8
    Nonconformist Narf's Avatar
    Join Date
    Aug 2005
    Posts
    174
    I wouldnt want a released app to bomb where I could help it.
    Me neither, that's why I made it clear that real world code has to die gracefully. For whatever definition of 'graceful' you pick. But the sad truth is that if a memory allocation fails, there's usually not much left that the program can do except terminate. You can warn the user and try to save as much state as possible, but even that might fail unless you have some extra memory saved up for graceful termination. Let's say you want to warn the user that a fatal error happened and you use cerr to do it. Well, there's nothing stopping cerr from trying to allocate memory to service your request. If that fails too, you crash. So notification is out unless you can guarantee that it can be done safely in the handling of an exception.

    Saving state is easier because you can set aside some recovery memory to handle the necessary operations for closing the program without loss. It's still annoying to the user, but at least nothing is destroyed in the process. Sure, you can try to recover by trying to allocate smaller chunks in light of fragmentation, or releasing unused memory and trying again, but in my experience, the chance of these solutions working is slim. And you're back to square one, terminating gracefully.
    Just because I don't care doesn't mean I don't understand.

  9. #9
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >Do you know of a remotely common OS that doesn't reclaim a process' memory on termination?
    Windows 98 ?

  10. #10
    Registered User
    Join Date
    Aug 2003
    Posts
    470
    Me neither, that's why I made it clear that real world code has to die gracefully. For whatever definition of 'graceful' you pick. But the sad truth is that if a memory allocation fails, there's usually not much left that the program can do except terminate. You can warn the user and try to save as much state as possible, but even that might fail unless you have some extra memory saved up for graceful termination.
    As long as the output strings are static, you're probably OK with cerr.

    Let's say you want to warn the user that a fatal error happened and you use cerr to do it. Well, there's nothing stopping cerr from trying to allocate memory to service your request. If that fails too, you crash. So notification is out unless you can guarantee that it can be done safely in the handling of an exception.
    Some times the operation isn't essential to the user. For instance, if the user wants to show an about box and the construction call failes, the program could abort this operation, log the error in a text file, and then try to show a message box. Sure, the attempt to show the message box might fail, but a program that does nothing for a while is better than one that crashed. (Some systems might warn the user automatically. For instance, with XP the operation system automatically warns the user when memory is getting low. )

  11. #11
    Magically delicious LuckY's Avatar
    Join Date
    Oct 2001
    Posts
    856
    But the sad truth is that if a memory allocation fails, there's usually not much left that the program can do except terminate.
    While (true), there is always the option to (prompt the user to free up some resources and retry) or (terminate the application). Just something to think about. (Note: I'm not arguing for or against any of this discussion; this is just a potential option to consider if you would like to handle an allocation exception.)

  12. #12
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Quote Originally Posted by swoopy
    >Do you know of a remotely common OS that doesn't reclaim a process' memory on termination?
    Windows 98 ?
    Yes, but to my great joy, windows 98 is becoming less and less of a common OS each day that passes!


  13. #13
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by Narf
    Do you know of a remotely common OS that doesn't reclaim a process' memory on termination?
    Although it's probably optimistic to describe it as an OS, MS-DOS provides minimal support for reclaiming program memory on termination: it relies primarily on programs being well behaved. This is also true of windows before windows 95 (eg windows 3.1). And, yes, such older systems are still used out there.

    For applications that must run "on the metal" (e.g. applications that talk directly to the hardware, with a minimal executive, and therefore aren't executed in the context of an OS), it is generally necessary for application to clean up after itself.

Popular pages Recent additions subscribe to a feed