Pointer Scope Questions
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Pointer Scope Questions

  1. #1
    Join Date
    Feb 2012
    Posts
    1

    Pointer Scope Questions

    Hi,

    I'm relatively new to C++ ad i'm trying to make a winhttp wrapper class. The problem is that I have to put a reference back from inside a function. But then the pointer goes out of scope because you can't destroy it:

    Code:
    int WINAPI WinMain(HINSTANCE inst,HINSTANCE prev,LPSTR cmd,int show)
    {		
    	HTTPReq* tst = new  HTTPReq();
    	HTTPReq::REQUEST_CONTEXT* context=tst->Connect(L"arevico.com",80,L"Firefox",true);
    	tst->SendRequest(context,L"ahe",L"referer",L"?page=1");
          // here i want to be able to pass context (so actually a item in the list defined in the  class
    	Sleep(10000);
    	delete tst;	
    	return 0;
        }
    And the snipper from the class:

    Code:
    list<REQUEST_CONTEXT> requestcontexes; //
    CRITICAL_SECTION cs;
    HINTERNET hSession;
    
    REQUEST_CONTEXT* Connect(LPCWSTR servername,unsigned int port,LPCWSTR useragent,bool async=false){
    		REQUEST_CONTEXT cpContext;
    		EnterCriticalSection(&cs);
    		requestcontexes.push_front(cpContext);
    
    			REQUEST_CONTEXT* refContext=&requestcontexes.front(); //locally declared pointer should be destroyed later
    			hSession= WinHttpOpen(useragent,WINHTTP_ACCESS_TYPE_NO_PROXY,NULL,NULL,async ? WINHTTP_FLAG_ASYNC : NULL);
    			refContext->hConnect=WinHttpConnect(hSession,servername,port,0);
    			//delete refContext; //you cant do this here
    			LeaveCriticalSection(&cs);
    		return refContext;
    	}
    What is the best way in C++ standards to do this?

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,888

    Re: Pointer Scope Questions

    So long as that REQUEST_CONTEXT remains within the list and the list is not destroyed, the pointer to it will remain valid. (That's one of the nice properties of std::lists.) There is no need to delete the pointer, since you did not allocate it with new.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center